Debian Codegraph @

listings/chapter-10/grep-dictionary.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 /* Returns a non-zero value if and only if the WORD appears in
11 /usr/dict/words. */
12
13 int grep_for_word (const char* word)
14 {
15 size_t length;
16 char* buffer;
17 int exit_code;
18
19 /* Build up the string `grep -x WORD /usr/dict/words'. Allocate the
20 string dynamically to avoid buffer overruns. */
21 length =
22 strlen ("grep -x ") + strlen (word) + strlen (" /usr/dict/words") + 1;
23 buffer = (char*) malloc (length);
24 sprintf (buffer, "grep -x %s /usr/dict/words", word);
25
26 /* Run the command. */
27 exit_code = system (buffer);
28 /* Free the buffer. */
29 free (buffer);
30 /* If grep returned zero, then the word was present in the
31 dictionary. */
32 return exit_code == 0;
33 }
34