Name
fgetc
Synopsis
Reads a character from a file
#include <stdio.h> intfgetc
( FILE *fp
);
The fgetc()
function reads
the character at the current file position in the specified file,
and increments the file position.
The return value of fgetc()
has the type int
. If the file
position is at the end of the file, or if the end-of-file flag was
already set, fgetc()
returns
EOF
and sets the end-of-file
flag. If you convert the function’s return value to char
, you might no longer be able to
distinguish a value of EOF
from a
valid character such as '\xFF'
.
Example
FILE *fp;
int c;
char buffer[1024];
int i = 0;
/* ... Open input file ... */
while ( i < 1023 )
{
c =fgetc
( fp ); // Returns a character on success;
if (c == EOF) // EOF means either an error or end-of-file.
{
if (feof( fp ))
fprintf( stderr, "End of input.\n" );
else if ( ferror( fp ))
fprintf( stderr, "Input error.\n" );
clearerr( fp ); // Clear the file's error or EOF flag.
break;
}
else
{
buffer[i++] = (char) c; // Use value as char *after* checking for EOF.
}
}
buffer[i] = '\0'; // Terminate string.
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.