Name
getc
Synopsis
Reads a character from a file
#include <stdio.h> intgetc
( FILE *fp
);
The getc()
function is the
same as fgetc()
, except that it
may be implemented as a macro, and may evaluate its argument more
than once. If the argument is an expression with side effects, use
fgetc()
instead.
getc()
returns the
character read. A return value of EOF
indicates an error or an attempt to
read past the end of the file. In these cases, the function sets the
file’s error or end-of-file flag as appropriate.
Example
FILE *inputs[16];
int nextchar, i = 0;
/* ... open 16 input streams ... */
do {
nextchar =getc
( inputs[i++] ); // Warning: getc() is a macro!
/* ... process the character ... */
} while (i < 16);
The do
...while
statement in this example skips over
some files in the array if getc()
evaluates its argument more than once. Here is a safer version,
without side effects in the argument to getc()
:
for ( i = 0; i < 16; i++ ) {
nextchar =getc
( inputs[i] );
/* ... process the character ... */
}
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.