#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <string.h>
#define SEARCH_WORD "like"
int main(int argc, char *argv[])
{
size_t page = (size_t)sysconf(_SC_PAGESIZE);
printf("page size is %ld.\n", page);
int fd = open("./mmap.manual", O_RDONLY);
struct stat st;
fstat(fd, &st);
off_t offset = 0;
off_t aligned = offset & ~(page - 1);
/* offset for mmap() must be page aligned */
size_t length = st.st_size - offset;
void *addr = mmap(NULL, length + offset - aligned, PROT_READ,
MAP_PRIVATE, fd, aligned);
if (addr == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
int n = 0;
char *word = strstr(addr + offset - aligned, SEARCH_WORD);
while (word) {
n++;
word = strstr(word + strlen(SEARCH_WORD), SEARCH_WORD);
}
printf("there are %d `%s` word.\n", n, SEARCH_WORD);
close(fd);
munmap(addr, length);
exit(EXIT_SUCCESS);
}