fgetc() Read one character from a stream
fgetc() Read one character from a stream
fgetc() returns an unsigned char as int, or EOF at end-of-file or on error. Store it in int; use feof() and ferror() to distinguish the cause.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
int fgetc(FILE *stream);
⚙️ Parameters
| stream Required | An open stream available for input. |
|---|
Returns: Returns the character read as an unsigned char converted to int, or EOF on end-of-file or a read error.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
A B
⚠️ Warning Store the result in an int and test for EOF before converting it to char; storing it directly in char can lose the end-of-file or error indication.
💡 Tip The example uses an automatically removed temporary file and calls rewind() to return to the beginning before reading.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QWhy does fgetc return int instead of char?
AIt must represent every unsigned char value plus EOF. An int can hold both the character values and the negative EOF indicator.
QHow do I distinguish end-of-file from a read error when fgetc returns EOF?
AInspect the stream with feof() and ferror(): the former reports end-of-file, while the latter reports an I/O error.
QWhat is the difference between fgetc and getchar?
Agetchar() is equivalent to fgetc(stdin) and reads only standard input; fgetc() accepts any open input stream, so the same character-by-character logic can read files or stdin. Both return int, and callers must save the result and check for EOF.