Lesson content
Read, practise, then check your understanding
The standard I/O library represents a stream with FILE *. A stream buffers access to a file, terminal, pipe, or other implementation-defined destination. Always check operations and close owned streams.
Open modes
FILE *input = fopen("records.txt", "r");
FILE *output = fopen("report.txt", "w");
FILE *log = fopen("events.log", "a");
r requires an existing file. w creates or truncates. a creates if needed and writes at the end. Add + for update (reading and writing), and b for binary mode, which matters on platforms that translate text newlines.
fopen returns NULL on failure. Capture or report the error before later calls change it.
Text I/O
char line[256];
while (fgets(line, sizeof line, input) != NULL) {
fputs(line, output);
}
if (ferror(input)) {
perror("reading records.txt");
}
End-of-file is not itself an error. feof becomes true only after a read attempts to pass the end; do not write while (!feof(file)). Drive the loop from the read result.
fprintf and fscanf perform formatted I/O, but input conversions require careful widths and return-value checks. Line-oriented input followed by strtol or strtod is often easier to validate.
Binary I/O
size_t written = fwrite(values, sizeof values[0], count, output);
if (written != count) {
/* handle short write */
}
fread and fwrite transfer objects as bytes. Raw structure dumps are not portable serialization because of padding, byte order, and representation. Define an explicit format and encode individual fields.
Positioning and durability
fseek, ftell, and rewind manipulate the position of suitable streams. In portable binary code, only offsets obtained appropriately from the same stream are broadly safe.
fflush pushes C library output buffers, but successful return does not necessarily mean durable storage on physical media. Durability requires platform-specific synchronization when a system truly needs it.
Close and replace safely
fclose can fail while flushing buffered data, so check it for important output. To replace a critical file, write a temporary file, verify and close it, then rename according to platform guarantees. Never trust an external path blindly; consider traversal, permissions, symbolic links, and file-size limits.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.