Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <limits.h>
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <unistd.h>
- #define MAX_WORD_LENGTH 32
- int main (int argc, char **argv) {
- int ifd; /* input file descriptor */
- struct stat ss = {0}; /* struct stat */
- off_t offset = 0, /* offset from start of file */
- /* multiple of page-size in mapped file */
- pa_offset = offset & ~(sysconf (_SC_PAGE_SIZE) - 1);
- char *fptr = NULL; /* pointer to content in memory mapped file */
- if (argc < 2 ) { /* validate 1 argument given for filename */
- fprintf (stderr, "error: insufficient input,\n"
- "usage: %s filename\n", argv[0]);
- return 1;
- }
- /* open file read-only/validate file open for reading */
- if ((ifd = open (argv[1], O_RDONLY)) == -1) {
- perror ("open-argv[1]");
- return 1;
- }
- if (fstat (ifd, &ss) == -1) { /* fill/validate stat struct for file size */
- perror ("fstat-ifd");
- return 1;
- }
- /* mmap file to fptr/validate mapping succeeded */
- if ((fptr = mmap (NULL, ss.st_size + offset - pa_offset, PROT_READ,
- MAP_SHARED, ifd, pa_offset)) == (void *)-1) {
- perror ("mmap-ifd");
- return 1;
- }
- for (;;) { /* loop continually allowing user to enter searches */
- char word[MAX_WORD_LENGTH + 1] = "", /* buffer to hold word */
- *p = fptr; /* pointer to mmaped content */
- size_t count = 0, /* no. time word found */
- len = 0; /* word length */
- /* prompt for word to search, read/validate input */
- fputs ("\nenter word (zzz to quit): ", stdout);
- if (!fgets (word, sizeof word, stdin) || strncmp (word, "zzz", 3) == 0)
- break;
- word[(len = strcspn(word, "\n"))] = 0; /* trim \n from end, get len */
- while ((p = strstr (p, word))) { /* loop finding each match */
- /* if ((at beginning or prev char is space or punct) ||
- * (or next char after word is end, space or punct))
- */
- if (((p == fptr) ||
- (p > fptr && (isspace(*(p - 1)) || ispunct(*(p - 1))))) &&
- (!*(p + len) || isspace(*(p + len)) || ispunct(*(p + len))))
- count++; /* increment count */
- p += len; /* advance pointer to next after word */
- }
- if (count) /* if count not zero, output count - or not found */
- printf ("'%s' was found %zu times.\n", word, count);
- else
- printf ("word not found: '%s'.\n", word);
- }
- munmap (fptr, ss.st_size); /* unmap file */
- close (ifd); /* close file descriptor */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement