Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 21.5 Source Code 803


33 /*
34 * Given a keyword, scan the configuration file for a match
35 * and return the string value corresponding to the keyword.
36 *
37 * LOCKING: none.
38 */
39 static char *
40 scan_configfile(char *keyword)
41 {
42 int n, match;
43 FILE *fp;
44 char keybuf[MAXKWLEN], pattern[MAXFMTLEN];
45 char line[MAXCFGLINE];
46 static char valbuf[MAXCFGLINE];
47 if ((fp = fopen(CONFIG_FILE, "r")) == NULL)
48 log_sys("can’t open %s", CONFIG_FILE);
49 sprintf(pattern, "%%%ds %%%ds", MAXKWLEN-1, MAXCFGLINE-1);
50 match=0;
51 while (fgets(line, MAXCFGLINE, fp) != NULL) {
52 n =sscanf(line, pattern, keybuf, valbuf);
53 if (n == 2 && strcmp(keyword, keybuf) == 0) {
54 match=1;
55 break;
56 }
57 }
58 fclose(fp);
59 if (match != 0)
60 return(valbuf);
61 else
62 return(NULL);
63 }

[33 – 46] Thescan_configfilefunction searches through the printer configuration
file for the specified keyword.
[47 – 63] We open the configuration file for reading and build the format string
corresponding to the search pattern. The notation%%%dsbuilds a format
specifier that limits the string size so we don’t overrun the buffers used to store
the strings on the stack. We read the file one line at a time and scan for two
strings separated by white space; if we find them, we comparethe first string
with the keyword. If we find a match or we reach the end of the file, the loop
ends and we close the file. If the keywordmatches, we return a pointer to the
buffer containing the string after the keyword; otherwise, we returnNULL.
The string returned is stored in a static buffer (valbuf), which can be
overwritten on successive calls. Thus,scan_configfilecan’t be called by a
multithreaded application unless we take caretoavoid calling it from multiple
threads at the same time.
Free download pdf