Reading, Writing & EOF
Reading and writing files uses the same ideas as console I/O, with one extra rule: test the read function, not feof.
In plain English
Reading a file is like reading a book line by line. Always check that the page was actually read.
Character and string I/O
fgetc reads one character and returns EOF at end of file. fputc writes one character. fgets reads a line into a buffer with a size limit, and fputs writes a string. These functions work on any stream, including stdin and stdout, which is why the same helpers appear in console and file code.
FILE *fp = fopen("data.txt", "r");
char line[128];
if (fp) {
while (fgets(line, sizeof line, fp) != NULL) {
printf("%s", line);
}
fclose(fp);
}Formatted I/O and end of file
fprintf and fscanf are the file versions of printf and scanf. They use the same format strings. feof does not predict the end of file; it reports that a read already hit EOF. The reliable pattern is to test the read function's return value, then optionally check feof or ferror to understand why it stopped.
int value;
while (fscanf(fp, "%d", &value) == 1) {
printf("read %d\n", value);
}
if (feof(fp)) {
printf("end of file\n");
} else if (ferror(fp)) {
perror("read error");
}Key takeaways
- fgetc/fputc handle characters; fgets/fputs handle strings.
- fprintf/fscanf mirror printf/scanf for files.
- feof reports a past EOF, not an upcoming one.
- Loop on the read function's return value, not on feof.
Common pitfalls
- Looping on feof instead of the read function's return value.
- Forgetting to close the file after reading.
- Ignoring ferror when a read stops early.
Key focus
- Trace a read loop that stops at EOF.
- Expect questions on feof and ferror semantics.
Quick check
1. Which function reads a string from a file with a size limit?
2. What does feof(fp) report?