Lesson 6 of 6 · Strings, Structs and Files · 3 min read · Updated
Reading and writing files
Make your data survive after the program exits.
Everything so far vanished when the program ended. Files are how a program remembers. The pattern is always the same: open, use, close.
#include <stdio.h>
int main(void)
{
FILE *f = fopen("marks.txt", "w");
if (f == NULL) {
printf("Could not open the file\n");
return 1;
}
fprintf(f, "Priya 87\n");
fprintf(f, "Arun 73\n");
fclose(f);
return 0;
}
Warning
fopen returns NULL when it fails — a missing file, a wrong path, no permission. Always check before using the result, or the first fprintf dereferences NULL and crashes.
Reading it back
FILE *f = fopen("marks.txt", "r");
if (f == NULL) {
printf("No such file\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), f) != NULL) {
printf("%s", line);
}
fclose(f);
The modes
"r"— read. Fails if the file is not there."w"— write. Empties an existing file immediately."a"— append. Adds to the end, keeping what is there.
Warning
Opening an existing file with "w" erases it before you write a single byte. If you meant to add to it, use "a". This one has destroyed a lot of homework.
Note
Always fclose. Output is buffered, so data can still be sitting in memory rather than on disk until you close the file.
You open an existing file with fopen("data.txt", "w"). What happens to the old contents?
Where to go next
- Build a small student record program: add records, list them, save to a file, and load them back when it starts.
- Read a text file and count the lines, words, and characters.
- Look up
mallocandfree— dynamic memory is the natural next step once pointers make sense.
Create a free account to save your progress, or sign in.