Module 8 · Files, the Preprocessor and Program Organisation — topic 1 of 4
File Handling
Programs need data that outlives them. Learn to open, read, write, append and close files with FILE*, fopen, fprintf, fscanf, fgets, fread, fwrite and fseek, and to handle errors properly.
Learning objectives
- Open files in the correct mode and check for failure
- Read and write text files line by line and with formatted I/O
- Store and load structs in binary files with fread and fwrite
Definition
File handling in C uses streams of typeFILE *from<stdio.h>.fopenassociates a stream with a named file in a given mode; input/output functions read and write through the stream;fcloseflushes buffers and releases it.
Introduction
Variables disappear when the program ends. To keep a contact list, inventory or high score, you write it to a file and read it back next time. Every management-system project in this course stores its records in files.
C treats a file as a stream of bytes. You open the stream, read or write through it, and close it. The same functions you already know — printf, scanf, fgets — have file versions: fprintf, fscanf, fgets(buf, n, fp).
Why it matters
Persistence is what turns a toy program into a usable tool. File handling questions (copy a file, count lines, store records) are standard in exams.
Correct error handling — checking fopen's result and every read — prevents the most common crashes in file-based programs.
Detailed explanation
fopen returns NULL on failure (missing file, no permission). Always check it, and use perror("msg") to print the reason.
Text I/O: fprintf(fp, ...), fscanf(fp, ...), fputs(s, fp), fgets(buf, size, fp) and fgetc/fputc. fgets returns NULL at end of file, making while (fgets(line, sizeof line, fp)) the standard read loop.
Binary I/O: fwrite(ptr, size, count, fp) writes raw bytes of objects such as structs; fread reads them back. Both return the number of items transferred. Binary files are compact and fast but not portable between machines with different type sizes or byte order.
Positioning: fseek(fp, offset, SEEK_SET | SEEK_CUR | SEEK_END) moves within a file, ftell reports the position and rewind returns to the start. This enables random access to the n-th record: offset = n × sizeof(record).
fclose flushes buffered output and frees the stream. Data may be lost if a program exits without closing (or flushing) a written file.
Syntax
- Never use
feofas the loop condition; test the read function's return value instead. - Use
"rb"/"wb"for binary data so Windows does not translate newline bytes. - Close every file you open.
Code examples
Write then read a text file
1: Arrays 2: Pointers 3: Structures
Handling a missing file
could not open file
In real programs perror adds the system's reason, such as “No such file or directory”.
More examples
Binary records with random access
wrote 3 records file is 96 bytes = 3 records record 2: Notebook 45.50 1 Pen 10.00 2 Notebook 39.99 3 Stapler 120.00
Step-by-step explanation
fwrite(stock, sizeof stock[0], 3, fp)writes the three structs as raw bytes in one call."rb+"opens for reading and writing without truncating.- Seeking to the end and calling
ftellgives the file size: 3 records × 32 bytes each on this platform. - Record n (0-based) starts at byte
n * sizeof(Item), sofseekjumps straight to the second record. - Writing at the same offset updates the record in place;
rewindthen re-reads every record. freadreturns 1 for each record read and 0 at end of file, which ends the loop.
Expected output
Running “Binary records with random access” prints exactly:
Practical applications
- Databases store fixed-size pages and seek to them by offset.
- Log files are opened in append mode so every run adds to the end.
- Configuration and CSV files are read line by line with
fgets.
Best practices
- Check every
fopen, read and write result. - Use text files for human-readable data and binary files for fixed-size records.
- Write to a temporary file and rename it to replace data safely.
Common mistakes
Not checking fopen
Avoid
Prefer
If the file is missing, fp is NULL and the read crashes.
Looping on feof
Avoid
Prefer
feof becomes true only after a read fails, so the last line is processed twice.
Opening with "w" to update
Avoid
Prefer
Mode "w" truncates an existing file to zero length.
Important notes
- Struct layout (padding, sizes, byte order) can differ between compilers, so binary files written by one platform may not be readable on another.
fseekwith offsets other than 0 or a value fromftellis not portable on text streams; use binary mode for random access.
Key takeaways
fopenwith a mode; check forNULL;fclosewhen done.- Read text with
while (fgets(...)), neverwhile (!feof(...)). fwrite/freadplusfseekgive random access to binary records.
Try it yourself
- 1Write a program that counts the lines, words and characters in a text file (like the Unix
wccommand). - 2Copy one file to another character by character with
fgetc/fputc.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat happens when a file that exists is opened with mode "w"?
- BeginnerWhat does `fopen` return when it cannot open a file?
- ModerateWhy does `while (!feof(fp)) { fgets(line, sizeof line, fp); printf("%s", line); }` print the last line twice?