How to Use fgetc in C: Read Characters from a File
In C,
fgetc reads the next character from a file stream and returns it as an int. You use it by passing a FILE* pointer opened with functions like fopen. It returns EOF when the end of the file is reached or an error occurs.Syntax
The fgetc function reads one character from the given file stream and returns it as an int. If it reaches the end of the file or an error happens, it returns EOF.
FILE *stream: A pointer to the file opened for reading.- Returns: The next character as an
int, orEOFon end of file or error.
c
int fgetc(FILE *stream);Example
This example opens a text file named example.txt, reads it character by character using fgetc, and prints each character to the screen until the end of the file.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } int ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); } fclose(file); return 0; }
Output
Hello, world!
This is a test file.
Common Pitfalls
- Not checking if the file was opened successfully before calling
fgetc. - Using
chartype to store the result offgetccan cause errors becausefgetcreturns anintto distinguishEOF. - Not handling
EOFproperly can lead to infinite loops or reading invalid data.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } // Wrong: using char to store fgetc result // char ch; // while ((ch = fgetc(file)) != EOF) { // putchar(ch); // } // Right: use int to store fgetc result int ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); } fclose(file); return 0; }
Quick Reference
fgetc Cheat Sheet:
| Usage | Description |
|---|---|
fgetc(file) | Reads next character from file stream |
Returns int | Character read or EOF if end or error |
Use int ch = fgetc(file); | Store result in int to detect EOF |
Check file != NULL | Ensure file opened before reading |
Loop with while ((ch = fgetc(file)) != EOF) | Read until end of file |
Key Takeaways
Always store the result of fgetc in an int to detect EOF correctly.
Check if the file opened successfully before using fgetc.
Use a loop with fgetc to read characters until EOF is reached.
fgetc reads one character at a time from the file stream.
EOF signals the end of the file or an error during reading.