SyntaxPilot
Courses/C Programming/Lesson 15

C Programming · Lesson 15 of 30 · 11 min

File handling

queued

These are the notes for C episode 15. Every program so far forgot everything the moment it ended. A chai shop's billing program adds up Monday's sales, and on Tuesday morning the total is zero. You find out why (variables live in RAM), and invent files to fix it: open with fopen, write with fprintf, close with fclose, read back with fgets and fscanf until EOF. Then you meet the mode that silently wipes your data ("w"), the one that keeps it ("a"), the missing file that crashes the program (NULL), and binary files with fwrite and fread. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown. Each run of the online compiler starts in a fresh, empty folder, so every program here writes its file first and then reads it in the same run.

The problem: where did yesterday's sales go?

On Monday, the shop's billing program reads every sale and adds it up:

#include <stdio.h>

int main() {
    int total = 0, amount;
    while (scanf("%d", &amount) == 1)
        total += amount;
    printf("Total today: Rs %d\n", total);
    return 0;
}

Input 120 80 250, output:

Total today: Rs 450

At night the shop closes and the computer is switched off. On Tuesday the owner runs the same program, with no sales yet (empty input):

Total today: Rs 0

Monday's 450 rupees are gone, and nothing in the code can bring them back.

Why it happened: RAM vs the disk

RAM (memory) Disk (SSD / hard disk)
Speed Very fast Slower
When the program ends Handed back to the system: the data is gone Kept
When the power goes off Wiped Kept
Where your data lives Every variable, array, struct, and even malloc'd memory (episode 14) Files

Idea: before the program ends, write the data into a file on the disk. Next time, read it back.

Writing a file: fopen, fprintf, fclose

Real-life example: the shop's register book.

At the shop In C
Open the register book to write in it FILE *fp = fopen("sales.txt", "w"); gives you a file pointer
Write each sale: "Chai 20" fprintf(fp, "Chai 20\n"); is printf into the file
Close the book so the page is saved fclose(fp); saves everything and lets the file go
#include <stdio.h>

int main() {
    FILE *fp = fopen("sales.txt", "w");
    fprintf(fp, "Chai 20\n");
    fprintf(fp, "Samosa 15\n");
    fprintf(fp, "Biscuit 10\n");
    fclose(fp);
    printf("Saved to sales.txt\n");
    return 0;
}

Output on the screen:

Saved to sales.txt

The sales didn't print on the screen: they went into sales.txt, which now contains:

Chai 20
Samosa 15
Biscuit 10

Key points:

  • FILE is a type defined in stdio.h. fopen returns a FILE *, a file pointer: a handle you pass to every other file function.
  • The first argument of fopen is the file name, the second is the mode, a string in double quotes ("w", not 'w').
  • fprintf(fp, ...) is exactly printf(...) with the file pointer first. (printf(...) is really fprintf(stdout, ...).)
  • fclose(fp) matters: writes are collected in a buffer in memory and sent to the disk in chunks. fclose flushes that buffer and releases the file. If a program crashes before the buffer is flushed, the last writes can be lost.

Reading a file back

Open the same file with mode "r" (read). Two ways to read:

Function Reads At the end of the file it returns
fgets(line, size, fp) One whole line into a char array (at most size - 1 chars), keeping the \n NULL
fscanf(fp, "%s %d", ...) Values, exactly like scanf, but from the file EOF (which is -1)

The pattern: loop until the read fails, and you have read the whole file.

Line by line with fgets

#include <stdio.h>

int main() {
    FILE *fp = fopen("sales.txt", "w");
    fprintf(fp, "Chai 20\nSamosa 15\nBiscuit 10\n");
    fclose(fp);

    char line[50];
    fp = fopen("sales.txt", "r");
    while (fgets(line, sizeof line, fp) != NULL)
        printf("Read: %s", line);
    fclose(fp);
    return 0;
}

Output:

Read: Chai 20
Read: Samosa 15
Read: Biscuit 10

The printf has no \n: fgets keeps the newline that was in the file. sizeof line is 50, so a line longer than 49 characters would come in pieces.

Values with fscanf, until EOF

The owner wants a total, so we need the numbers. %19s reads one word of at most 19 characters, so it always fits in item[20] (19 + the '\0').

#include <stdio.h>

int main() {
    FILE *fp = fopen("sales.txt", "w");
    fprintf(fp, "Chai 20\nSamosa 15\nBiscuit 10\n");
    fclose(fp);

    char item[20];
    int price, total = 0;
    fp = fopen("sales.txt", "r");
    while (fscanf(fp, "%19s %d", item, &price) == 2) {
        printf("%-8s Rs %d\n", item, price);
        total += price;
    }
    int r = fscanf(fp, "%19s %d", item, &price);
    printf("At the end fscanf gives %d (EOF)\n", r);
    fclose(fp);
    printf("Total: Rs %d\n", total);
    return 0;
}

Output:

Chai     Rs 20
Samosa   Rs 15
Biscuit  Rs 10
At the end fscanf gives -1 (EOF)
Total: Rs 45

fscanf returns how many values it filled: 2 while there are sales, and EOF (-1) when the file has nothing left. Testing == 2 (not just "not EOF") also stops the loop if a line is badly formed.

The next problem: "w" wipes, "a" appends

The shop now saves every day. Monday opens the file with "w" and writes its total. Tuesday runs the same code: "w" again.

#include <stdio.h>

void show(void) {
    char line[50];
    FILE *fp = fopen("sales.txt", "r");
    while (fgets(line, sizeof line, fp)) printf("  %s", line);
    fclose(fp);
}

int main() {
    FILE *fp = fopen("sales.txt", "w");      // Monday
    fprintf(fp, "Monday 450\n");
    fclose(fp);

    fp = fopen("sales.txt", "w");            // Tuesday
    fprintf(fp, "Tuesday 380\n");
    fclose(fp);

    printf("File now has:\n");
    show();
    return 0;
}

Output:

File now has:
  Tuesday 380

Monday is gone, with no error and no warning: mode "w" creates the file, and if it already exists, empties it first. The fix is one letter. Change Tuesday's "w" to "a" (append):

    fp = fopen("sales.txt", "a");            // Tuesday

Output:

File now has:
  Monday 450
  Tuesday 380

File modes

Mode Meaning File missing File exists
"r" Read fopen returns NULL Read from the start
"w" Write Created Wiped, then written from the start
"a" Append Created Kept; every write goes to the end
"r+" Read and write NULL Kept; read/write from the start
"w+" Read and write Created Wiped
"a+" Read and append Created Kept; reads anywhere, writes at the end
add b Binary: "rb", "wb", "ab", "rb+" ...

Rule of thumb: a log or a record you keep adding to, use "a". A file you rebuild from scratch each time, use "w".

A missing file: fopen returns NULL

The owner wants to read stock.txt, but nobody ever created it:

#include <stdio.h>

int main() {
    char line[50];
    FILE *fp = fopen("stock.txt", "r");
    fgets(line, sizeof line, fp);
    printf("%s", line);
    fclose(fp);
    return 0;
}

Output:

Segmentation fault

When fopen can't open a file, it doesn't stop the program: it returns NULL, a pointer to nothing. fgets then reads from nothing, and the program crashes. Always check:

#include <stdio.h>

int main() {
    char line[50];
    FILE *fp = fopen("stock.txt", "r");
    if (fp == NULL) {
        perror("stock.txt");
        return 1;
    }
    while (fgets(line, sizeof line, fp)) printf("%s", line);
    fclose(fp);
    return 0;
}

Output (on the error stream, exit code 1):

stock.txt: No such file or directory

perror(text) prints your text, a colon, and the system's reason for the last failure (stored in errno). fopen can fail for other reasons too, and perror names them: a wrong folder (No such file or directory), no permission (Permission denied), opening a folder for writing (Is a directory). Returning 1 from main tells whoever ran the program that it failed.

Binary files: fwrite and fread

Text file Binary file
How 450 is stored 3 characters: '4', '5', '0' The raw bytes of the int, exactly as in memory
Open it in Notepad Readable Junk
Functions fprintf, fgets, fscanf fwrite, fread
Good for Logs, settings, anything people read Saving and loading whole structs or arrays fast
Portable? Yes Depends on the struct layout and the machine

fwrite(pointer, size of one item, how many items, fp) writes the bytes; fread with the same arguments reads them back and returns how many items it really read.

#include <stdio.h>

typedef struct {
    char name[20];
    int price;
} Item;

int main() {
    Item menu[3] = {{"Chai", 20}, {"Samosa", 15}, {"Biscuit", 10}};
    FILE *fp = fopen("menu.bin", "wb");
    fwrite(menu, sizeof(Item), 3, fp);
    fclose(fp);

    Item back[3];
    fp = fopen("menu.bin", "rb");
    size_t n = fread(back, sizeof(Item), 3, fp);
    fclose(fp);
    printf("Read %zu items of %zu bytes\n", n, sizeof(Item));
    for (int i = 0; i < 3; i++)
        printf("%s %d\n", back[i].name, back[i].price);
    return 0;
}

Output:

Read 3 items of 24 bytes
Chai 20
Samosa 15
Biscuit 10

Each Item is 24 bytes (20 for the name + 4 for the price), so menu.bin is 72 bytes. The warning: if you change the struct (add a member, change a size) or move the file to a machine with a different layout, old binary files no longer load correctly. For data people need to read or share, prefer text.

Common mistakes (and the real messages)

Mistake What you see Why Fix
Reading after fopen(..., "r") without a check, file missing Segmentation fault fopen returned NULL if (fp == NULL) { perror("name"); return 1; }
fopen("sales.txt", "w") on a file you wanted to keep No error: the old data is gone "w" empties an existing file Use "a" to add to the end
fopen("sales.txt", 'w') warning: passing argument 2 of 'fopen' makes pointer from integer without a cast [-Wint-conversion], then Segmentation fault The mode must be a string, 'w' is a single char (an int) "w" in double quotes
printf("%s\n", line) after fgets No error: a blank line after every line fgets keeps the \n from the file printf("%s", line)
Forgetting fclose Usually nothing, until the last writes go missing after a crash, or the program runs out of open files Data waits in the buffer; each open file uses a slot fclose every file you fopen
char item[5] with fscanf(fp, "%s", item) and a long word Memory overwritten, random bugs %s has no length limit Give a width: %4s for char item[5]
while (!feof(fp)) { fscanf(...); ... } The last record processed twice feof only becomes true after a read fails Loop on the read's return value

The blank-line mistake, verified: with printf("%s\n", line) the file Chai 20 / Samosa 15 prints as

Chai 20

Samosa 15

Mini project: a shop's sales log

Each sale is typed in as an item and a price. The program appends every sale to sales.txt, then reads the whole file back and prints a report.

#include <stdio.h>

int main() {
    char item[20];
    int price, count = 0, total = 0, best = 0;

    FILE *fp = fopen("sales.txt", "a");
    while (scanf("%19s %d", item, &price) == 2)
        fprintf(fp, "%s %d\n", item, price);
    fclose(fp);

    fp = fopen("sales.txt", "r");
    if (fp == NULL) { perror("sales.txt"); return 1; }
    while (fscanf(fp, "%19s %d", item, &price) == 2) {
        count++;
        total += price;
        if (price > best) best = price;
    }
    fclose(fp);
    printf("Sales: %d\n", count);
    printf("Total: Rs %d\n", total);
    printf("Biggest sale: Rs %d\n", best);
    return 0;
}

Input:

Chai 20
Samosa 15
Thali 120
Chai 20
Lassi 40

Output:

Sales: 5
Total: Rs 215
Biggest sale: Rs 120

On your own computer, run it again the next day with new sales: because of "a", they are added after the old ones, and the report covers both days. (The online compiler starts every run in an empty folder, so try that part locally.) Extension: also print the average sale, (float)total / count.

Practice

  1. Save 5 students' names and marks to marks.txt.
  2. Read it back and print the class average.
  3. Count the lines in a file with fgets.
  4. Write a Student struct array with fwrite and read it back with fread.
Solutions

All four in one program (verified):

#include <stdio.h>

typedef struct {
    char name[20];
    int marks;
} Student;

int main() {
    // 1. save 5 students' names and marks
    Student s[5] = {{"Asha", 82}, {"Ravi", 67}, {"Meera", 91}, {"Kabir", 74}, {"Zoya", 88}};
    FILE *fp = fopen("marks.txt", "w");
    if (fp == NULL) { perror("marks.txt"); return 1; }
    for (int i = 0; i < 5; i++) fprintf(fp, "%s %d\n", s[i].name, s[i].marks);
    fclose(fp);

    // 2. read them back and print the class average
    char name[20];
    int m, n = 0, sum = 0;
    fp = fopen("marks.txt", "r");
    if (fp == NULL) { perror("marks.txt"); return 1; }
    while (fscanf(fp, "%19s %d", name, &m) == 2) { sum += m; n++; }
    fclose(fp);
    printf("Average of %d students: %.2f\n", n, (float)sum / n);

    // 3. count the lines with fgets
    char line[100];
    int lines = 0;
    fp = fopen("marks.txt", "r");
    while (fgets(line, sizeof line, fp)) lines++;
    fclose(fp);
    printf("marks.txt has %d lines\n", lines);

    // 4. a Student array with fwrite / fread
    fp = fopen("marks.bin", "wb");
    fwrite(s, sizeof(Student), 5, fp);
    fclose(fp);
    Student back[5];
    fp = fopen("marks.bin", "rb");
    size_t got = fread(back, sizeof(Student), 5, fp);
    fclose(fp);
    printf("fread got %zu students; last: %s %d\n", got, back[4].name, back[4].marks);
    return 0;
}

Output:

Average of 5 students: 80.40
marks.txt has 5 lines
fread got 5 students; last: Zoya 88

marks.bin is 120 bytes: 5 students × 24 bytes. Counting lines with fgets assumes no line is longer than 99 characters; a longer one would be counted more than once.

Quick quiz

What is in a.txt at the end?

f = fopen("a.txt", "w"); fprintf(f, "1\n"); fclose(f);
f = fopen("a.txt", "a"); fprintf(f, "2\n"); fclose(f);
f = fopen("a.txt", "w"); fprintf(f, "3\n"); fclose(f);
  • A. 1 2 3
  • B. 3
  • C. 1 2
  • D. 2 3
Answer

B: only 3. The append added 2 after 1, but the last fopen uses "w", which wipes the file before writing 3. (Verified: reading the file back prints just 3.)

Interview questions

  • Why is data in variables lost when a program ends? Where should it go to survive?
  • What does fopen return, and what does it return on failure?
  • What is the difference between modes "w" and "a"? Between "r+" and "w+"?
  • What is the difference between fgets and fscanf? Why is fgets safer than gets?
  • What are EOF and its value? What does fgets return at the end of a file?
  • Why is while (!feof(fp)) usually wrong?
  • What does fclose do, and what can happen if you forget it?
  • What is a file buffer? What does fflush do?
  • What is the difference between a text file and a binary file?
  • What do fwrite and fread return?
  • What does perror print? What is errno?
  • What are stdin, stdout and stderr?

Glossary

Term Meaning Example
RAM Fast, temporary memory where variables live; wiped when the program ends int total
Disk Slower storage that keeps data with the power off SSD, hard disk
File A named block of data on the disk sales.txt
FILE The type in stdio.h that describes an open file FILE *fp
File pointer A FILE *: the handle you pass to every file function fp
Stream C's name for a source or destination of data, such as an open file stdin, stdout, fp
stdin / stdout / stderr The three streams every program starts with: keyboard input, screen output, error output printf writes to stdout
fopen Opens a file in a mode; returns a FILE * or NULL fopen("sales.txt", "a")
Mode A string saying how to open the file "r", "w", "a", "rb"
Append Add to the end, keeping what is already there mode "a"
fprintf printf into a file fprintf(fp, "%d\n", x)
fclose Flushes and closes a file fclose(fp)
Buffer Memory where writes wait before going to the disk in one go flushed by fclose / fflush
fgets Reads one line (keeps the \n); NULL at the end fgets(line, sizeof line, fp)
fscanf scanf from a file; returns how many values it filled fscanf(fp, "%19s %d", item, &price)
EOF "End of file", a constant equal to -1, returned when nothing is left to read fscanf(...) == EOF
NULL A pointer to nothing; what fopen returns when it fails if (fp == NULL)
perror Prints your text and the system's reason for the last error stock.txt: No such file or directory
errno The global error number that perror explains set by a failed fopen
Text file Stores data as readable characters 450 is '4' '5' '0'
Binary file Stores the raw bytes from memory menu.bin
fwrite / fread Write / read raw items; return the number of items done fwrite(menu, sizeof(Item), 3, fp)
Segmentation fault The crash when a program touches memory it may not use reading from a NULL file

Summary

  • Variables (and malloc'd memory) live in RAM and vanish when the program ends; files on the disk keep data.
  • fopen(name, mode) gives a FILE *; fprintf writes; fclose flushes and closes.
  • fgets reads a line (NULL at the end); fscanf reads values (EOF, -1, at the end). Loop on the read's return value.
  • "r" reads, "w" wipes and writes, "a" appends. Use "a" for logs.
  • fopen returns NULL when it fails: always check, and explain it with perror.
  • fwrite / fread save and load whole structs in one call; binary files are fast but tied to the struct layout.

Next episode: the preprocessor and macros: what #include and #define really do before the compiler even starts, and the traps inside macros.