HP C/iX Library Reference Manual (30026-90004)
Chapter 5 165
HP C/iX Library Function Descriptions
fprintf
}
file = fopen(argv[1], "r");
if(file == NULL) {
fprintf(stderr, "Can't open %s.\n", argv[1]);
exit(1);
}
while(fscanf(file, "%*s") != EOF)
count;
fprintf(stdout, "Number of words found: %d\n", count);
exit(0);
}
This program counts the number of "words" in the file specified as its only argument. A
word is defined as a string of nonspace characters.
In this program, fprintf() directs error messages to stderr. Error output is written on a
different stream than normal output; the error output (or the normal output) can be
redirected to another destination. For example, invoking the program with stderr set to
the file errmsgs causes all output from erroneous conditions to be collected in the errmsgs
file. In this example, this capability is trivial because the program terminates on any error.
However, this is a very useful capability for programs that output any number of warnings
without terminating. Not only does this command keep the desired output uncluttered
with error messages, but it also enables you to save the output. Thus, it is good
programming practice to write error messages and warnings on stderr and to use stdout
(or any destination file) to output normal data.
See Also
putc(), scanf(), printf(), vprintf(), vfprintf(), fscanf(), ANSI C 4.9.6.1, POSIX.1
8.1