MODULE 3 • LESSON 12
Every program you have written so far forgets everything when it ends. Type in thirty marks, close the program, and the marks are gone. Real programs need persistent storage: data that survives after the program stops and is there next time it runs. The simplest way to achieve this is a file on disk.
In this lesson you will use text files: files of readable characters arranged in lines, which you could also open in Notepad. You will learn the five basic file operations named in the syllabus: open, close, read, write and append. By the end you will save a list of records to a file and load them back, which is the heart of every simple database program.
What you will learn
- Why files are needed, and what a text file is.
- How to declare a file pointer and open a file with fopen in “r”, “w” or “a” mode, checking for NULL.
- How to write to a file with fprintf, and read from it with fscanf and fgets.
- How to read a file of unknown length, using the value returned by fscanf or fgets.
- Why every file must be closed with fclose.
- How to save an array of records to a text file and load it back.
Part 1: Files and file pointers
Main memory (RAM) is fast but volatile: its contents disappear when the program ends or the power goes off. Secondary storage such as a hard disk or flash drive keeps data permanently, organised into named files. A program uses a file in three stages: open it (connect the program to the file), read or write it, and close it (finish and disconnect).
A text file stores characters, one line after another, each line ending with a newline character. The number 78 is stored as the two characters 7 and 8, not as a binary int. Text files are easy to create, read and check by eye, and they can be shared between programs and languages. (Binary files, which store values exactly as they are in memory, are covered in the Go further links.)
In C, file work uses functions from stdio.h, the same header as printf and scanf. A program refers to an open file through a file pointer, a variable of type FILE *:
FILE *fp;
Think of fp as a handle or ticket for the file: fopen gives you the handle, and every later operation on that file uses it. The star means it is a pointer; you do not need to know more about pointers to use it.
Part 2: Opening and closing
fp = fopen("scores.txt", "r");
fopen takes two strings: the file name (which may include a folder path) and the mode. It returns a file pointer, or NULL if the file could not be opened.
| Mode | Meaning | If the file exists | If it does not exist |
| “r” | Read | Opened at the start for reading | fopen returns NULL |
| “w” | Write | Contents erased; writing starts afresh | A new empty file is created |
| “a” | Append | Kept; writing goes at the end | A new empty file is created |
The “w” row is the dangerous one: opening an existing file with “w” erases it immediately, before you write a single character. Use “a” when you want to add to existing data.
Always check for NULL. A file may be missing, misspelt, on a removed flash drive or in a folder you are not allowed to write to. Using a NULL file pointer makes the program crash. The standard pattern is:
fp = fopen("scores.txt", "r");
if (fp == NULL) {
printf("Cannot open file\n");
return 1;
}
When you have finished, call fclose(fp);. For speed, C collects output in a memory buffer and writes it to disk in larger blocks. fclose writes whatever is still in the buffer and releases the file so other programs can use it. A program that forgets fclose may leave a file incomplete or empty. Close every file you open, as soon as you have finished with it.
Try it 1File mode lab
Two files are on the disk. Use the buttons as if they were statements in a program, and complete the four missions. Watch what each mode does to the file, and when written lines actually reach the disk.
Program output
Part 3: Writing and reading
Writing. fprintf works exactly like printf, with the file pointer added as the first argument: fprintf(fp, "%s %d\n", name, score);. Whatever printf would have shown on the screen goes into the file instead. Remember the \n, or all your data ends up on one line. Separate values with spaces so they can be read back.
Reading values. fscanf works like scanf, from the file: fscanf(fp, "%20s %d", name, &score);. The same rules apply: the address operator for number variables, none for strings, and %s stops at a space, so a name stored in a text file this way must be one word (use Keisha_Ann, or put each field on its own line and read it with fgets).
Reading lines. fgets(line, 81, fp) reads one whole line, spaces and all, up to 80 characters, including the newline at the end. It is the best choice when you want to display a file or process it line by line.
Reading a file of unknown length
Usually you do not know how many lines a file contains. The answer is to use the value each read function returns:
- fscanf returns the number of items it successfully read, or EOF (a special negative value) if the end of the file was reached first. So
while (fscanf(fp, "%20s %d", name, &score) == 2)keeps going as long as a complete line was read. - fgets returns NULL at the end of the file, so
while (fgets(line, 81, fp) != NULL)processes every line.
Testing the result of the read itself is safer than using the feof function before reading, which is a common source of a “last line processed twice” bug. Each read continues from where the previous one stopped, because the file keeps track of its current position.
Worked example 1: write a file, then read it back
#include <stdio.h>
int main(void)
{
FILE *fp;
char name[21];
int score, total = 0, n = 0;
fp = fopen("scores.txt", "w");
if (fp == NULL) {
printf("Cannot create file\n");
return 1;
}
fprintf(fp, "Keisha 78\n");
fprintf(fp, "Ravi 64\n");
fprintf(fp, "Ana 91\n");
fclose(fp);
fp = fopen("scores.txt", "r");
if (fp == NULL) {
printf("Cannot open file\n");
return 1;
}
while (fscanf(fp, "%20s %d",
name, &score) == 2) {
printf("%-8s%4d\n", name, score);
total += score;
n++;
}
fclose(fp);
printf("Read %d scores, total %d\n",
n, total);
return 0;
}
Output:
Keisha 78 Ravi 64 Ana 91 Read 3 scores, total 233
The program creates scores.txt with three lines, closes it, then opens it again for reading. The while loop calls fscanf until it no longer returns 2, so it handles three lines here and would handle three hundred without any change. If you open scores.txt in a text editor after running the program, you will see the three lines exactly as fprintf wrote them.
Try it 2File tracer
Step through a read loop and a sequence of opens. The file’s contents are shown as a variable.
Output
Worked example 2: appending, reading lines and a missing file
#include <stdio.h>
void showFile(char fname[])
{
FILE *fp = fopen(fname, "r");
char line[81];
int n = 0;
if (fp == NULL) {
printf("No file: %s\n", fname);
return;
}
while (fgets(line, 81, fp) != NULL) {
n++;
printf("%d: %s", n, line);
}
fclose(fp);
}
int main(void)
{
FILE *fp;
fp = fopen("log.txt", "w");
fprintf(fp, "Mon rain 24.5\n");
fprintf(fp, "Tue sun 31.0\n");
fclose(fp);
showFile("log.txt");
fp = fopen("log.txt", "a");
fprintf(fp, "Wed cloud 28.0\n");
fclose(fp);
printf("After append:\n");
showFile("log.txt");
showFile("missing.txt");
return 0;
}
Output:
1: Mon rain 24.5 2: Tue sun 31.0 After append: 1: Mon rain 24.5 2: Tue sun 31.0 3: Wed cloud 28.0 No file: missing.txt
showFile is a reusable function: it opens any file for reading, prints every line with a line number using fgets, and closes it. Notice that printf uses "%d: %s" with no \n, because fgets keeps the newline from the file. The second fopen uses "a", so Wednesday is added after the first two lines. The last call shows the NULL check doing its job: instead of crashing, the program reports the missing file and carries on. To keep main short, it does not check the two fopen calls that create log.txt; a full program should check every fopen.
Part 4: Saving and loading records
Text files and records (Lesson 11) work together naturally. The usual format is one record per line, with the fields separated by spaces (or commas, or tabs). Saving is a loop of fprintf calls, one per record. Loading is a while loop of fscanf calls, storing each line in the next array element, counting as it goes, and stopping either at the end of the file or when the array is full.
Worked example 3: a members file
#include <stdio.h>
typedef struct {
char name[21];
int age;
float fee;
} Member;
int save(char fn[], Member m[], int n)
{
int i;
FILE *fp = fopen(fn, "w");
if (fp == NULL) {
return 0;
}
for (i = 0; i < n; i++) {
fprintf(fp, "%s %d %.2f\n",
m[i].name, m[i].age,
m[i].fee);
}
fclose(fp);
return 1;
}
int load(char fn[], Member m[], int max)
{
int n = 0;
FILE *fp = fopen(fn, "r");
if (fp == NULL) {
return 0;
}
while (n < max
&& fscanf(fp, "%20s %d %f",
m[n].name, &m[n].age,
&m[n].fee) == 3) {
n++;
}
fclose(fp);
return n;
}
int main(void)
{
Member a[3] = {{"Devon", 15, 80.0},
{"Priya", 19, 120.0},
{"Joel", 17, 80.0}};
Member b[10];
int i, n;
if (!save("club.txt", a, 3)) {
printf("Save failed\n");
return 1;
}
n = load("club.txt", b, 10);
printf("Loaded %d members\n", n);
for (i = 0; i < n; i++) {
printf("%-7s%3d%8.2f\n", b[i].name,
b[i].age, b[i].fee);
}
return 0;
}
Output:
Loaded 3 members Devon 15 80.00 Priya 19 120.00 Joel 17 80.00
save writes the array to the file and returns 1 for success or 0 if the file could not be opened. load reads into a different array, b, and returns how many records it read. The condition n < max is tested first, so the loop never writes past the end of the array even if the file is longer than expected. The data went from memory, to disk, and back into memory: if main were split into two programs, the second could load what the first saved.
The file club.txt contains:
Devon 15 80.00 Priya 19 120.00 Joel 17 80.00
This is the plain text file approach to storing records. It is easy to check and edit, but the program has to read the whole file to find one record, and changing one record usually means loading everything, changing the array and saving the whole file again with "w". Databases (Unit 2) solve these problems on a larger scale.
Where is the file?
A file name with no folder, such as "club.txt", refers to the program’s current working directory. In Code::Blocks this is usually the project folder, not the folder holding the .exe, which surprises many students looking for their file. You can give a full path instead. On Windows the folder separator is a backslash, which must be doubled inside a C string: "C:\\data\\club.txt". A forward slash, "C:/data/club.txt", also works on Windows and is easier to type.
Designing a file format
Before writing save and load, decide exactly how each record will look in the file, and make sure both functions agree. Writing with "%s %d %.2f" and reading with "%20s %d %f" matches: three fields separated by spaces. If the save function writes the age before the name but the load function expects the name first, every record will be read wrongly and nothing will warn you.
Spaces are the easiest separator for fscanf, but they cannot appear inside a field. Two common alternatives are one field per line (read each field with fgets, so names can contain spaces) and comma-separated values, CSV, which spreadsheets such as Excel can open directly. Reading CSV needs a scanset such as %20[^,] to stop at a comma; that is beyond this lesson, but useful to know when you want to share data with a spreadsheet. A header line at the top of the file, such as a count of records or the field names, can also make a file easier to check and to load.
Common mistakes
| Mistake | Effect | Fix |
| Opening with "w" to add data | Old contents lost | Use "a" |
| No NULL check | Crash if the file is missing | if (fp == NULL) { … } |
| Forgetting fclose | File may be incomplete | Close every file you open |
| No \n in fprintf | Everything on one line | End each record with \n |
| Reading with "w" mode | Reads fail | Open with "r" |
| Spaces in a %s field | Fields read out of step | One-word values, or fgets per field |
| Loop on feof | Last record processed twice | Loop on the read’s return value |
Try it 3File practice
Pick a mode. "Modes" asks which fopen mode a task needs. "Returns" asks what fscanf returns.
Summary
| Idea | Remember |
| File pointer | FILE *fp; the handle for an open file. |
| fopen | "r" read, "w" new or erase, "a" add to the end; NULL on failure. |
| Write | fprintf(fp, format, values); end lines with \n. |
| Read | fscanf returns the items read or EOF; fgets returns NULL at the end. |
| Loop | while (fscanf(...) == number of items) or while (fgets(...) != NULL). |
| fclose | Flushes the buffer and releases the file. |
| Records | One record per line; save with a for loop, load with a while loop and a counter. |
Review questions
1. Why do programs need files?
Show answer
Data in main memory is lost when the program ends; a file on secondary storage keeps it permanently so it can be used again later.
2. State the difference between opening a file with "w" and with "a".
Show answer
"w" erases any existing contents (or creates a new file) and writes from the start; "a" keeps the existing contents and adds new data to the end.
3. Write a statement that opens results.txt for reading, and code that stops the program if it cannot be opened.
Show answer
fp = fopen("results.txt", "r");
if (fp == NULL) {
printf("Cannot open results.txt\n");
return 1;
}
4. Write a statement that writes a student’s name and mark to the file fp, on one line.
Show answer
fprintf(fp, "%s %d\n", name, mark);
5. Explain how a program can read every line of a file without knowing how many lines it has.
Show answer
Loop while the read succeeds: fscanf returns the number of items read (or EOF at the end), and fgets returns NULL at the end, so the loop stops automatically.
6. Why should a file be closed?
Show answer
fclose writes any data still held in the buffer to the disk and releases the file. Without it, data may be lost and the file may stay locked.
7. Write a code fragment that counts the lines in notes.txt.
Show answer
fp = fopen("notes.txt", "r");
if (fp != NULL) {
while (fgets(line, 81, fp) != NULL) {
count++;
}
fclose(fp);
}
8. A student’s program opens marks.txt with "w" each time it adds a new mark, and the file only ever contains one mark. Explain and fix.
Show answer
Each "w" open erases the file, so only the latest mark survives. Open the file with "a" to add marks to the end.
Homework
- Write a program that asks for five temperatures and saves them to temps.txt, one per line. Write a second program that reads temps.txt and prints the average.
- Write a program that appends a line with today’s date and a message to diary.txt each time it runs. Run it three times and check the file.
- Write int countWords(char fname[]) that returns the number of words in a text file, using fscanf with %s.
- Extend Worked example 3 with a menu: 1 add a member (append), 2 list all members, 3 show total fees, 4 quit.
- Write a program that copies one text file to another, line by line, and prints how many lines it copied.
Mastery quiz: Text files in C
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Text Files in C: Saving, Loading and Appending Data
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
CAPE 2024 Unit 1 Paper 02, Question 5(c). C statements to open a file for reading, append data to it and close it. Marks go for the FILE pointer, the correct mode string in fopen, a correct fprintf with the file pointer first, and fclose. Including a NULL check shows good practice.
Specimen Unit 1 Paper 01 (2021), Item 42. Choosing the right file mode for a task. Learn the r/w/a table, especially that "w" erases an existing file.
Specimen Unit 1 Paper 01 (2021), Item 23. Recognising what a short C fragment does. File fragments are a common choice: read each line, ask what it opens, what it writes or reads, and whether it closes.
When writing file code in an exam, write every step: declare FILE *, fopen with the mode, check NULL, read or write in a loop, fclose. Missing fclose is a frequently lost mark.
More worked answers are on the CS Solutions page.
Previous: Module 3 • Lesson 11 – Records in C: Grouping Data with struct. Next: Module 3 • Lesson 13 – Choosing a Programming Language: C, C++, Java, JavaScript and Python Compared.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 10: use text files to store data and records (file operations: open, close, read, write, append).
Video search terms
Search YouTube for: "C file handling fopen fprintf fscanf", "C read file until EOF", "C append to text file".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- Updated the copyright line.
2026/11/24
- First version of the lesson.
© 2026 islandclass.org
