TalentJR

⚙️ C programming basics · Class 10 · Lesson 5 of 18 · Free

File Handling in C – fopen, fprintf, fgets, fscanf, fwrite and fread

⏱ About 40 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Open, write, read and close text files with fopen, fprintf, fgets and fclose
  • Read numbers and words from a file with fscanf and stop at the right time
  • Choose the right file mode and save structs with fwrite and fread

You type 40 students' marks into your program, close it, and everything is gone. Variables live only while the program runs. Files let your program save data and read it back tomorrow, just like a register on the teacher's shelf.

How do you write to a file in C?

A file is opened with fopen(name, mode). It returns a FILE * (a pointer to a FILE), which you pass to every later file function. Mode "w" means write: it creates the file, or empties it if it already exists.

fopen returns NULL if it fails, for example when there is no permission. Always check it. fprintf works like printf, but writes into the file. fclose saves everything and closes the file.

You cannot see files in this browser box, so the program reads the file back and prints it. Here it uses fgets, which you met in Lesson 3.

Try it: add one more fprintf line for another day and run again.

⚙️ C — you can edit this code
Output
Monday: 38 present
Tuesday: 40 present

How do you read a file line by line in C?

Mode "r" opens a file for reading. fgets(line, size, f) reads one line, including its '\n'. When there are no more lines, it returns NULL, which ends the while loop.

This box comes with a file called notice.txt. The program prints each line with a line number. Because each line already ends with '\n', we print it with %s and no extra \n.

Try it: edit the notice.txt file, add a line, and run again.

🗂️ notice.txt — a file your program can open
School closed on Friday for Diwali.
Unit test starts on Monday.
Bring your library books back.
⚙️ C — you can edit this code
Output
1: School closed on Friday for Diwali.
2: Unit test starts on Monday.
3: Bring your library books back.
The notice has 3 lines.

How do you read numbers from a file with fscanf in C?

fscanf is scanf for files. fscanf(f, "%19s %d", name, &marks) reads one word and one number. %19s stops a long word from overflowing the 20-byte array.

fscanf returns how many values it filled. When it returns something other than 2, the file has ended (or has bad data), so the loop stops. This is the right way to control the loop.

Try it: add the line "Meera 97" to marks.txt and run again. Who is the topper now?

🗂️ marks.txt — a file your program can open
Riya 91
Aman 76
Zoya 94
Kabir 69
⚙️ C — you can edit this code
Output
Students: 4
Average: 82.5
Topper: Zoya with 94

What is the difference between "w" and "a" mode in C files?

"w" starts the file fresh every time; old contents are lost. "a" (append) keeps the old contents and adds new lines at the end. Use "a" for logs like a canteen's daily sales.

Other modes: "r+" reads and writes an existing file; "w+" and "a+" also allow reading. Add b, like "rb" or "wb", for binary files (next section).

Here each call to add_sale opens the file in "a" mode, writes one line and closes it.

Try it: change "a" to "w" in add_sale and run again. Only the last sale is left.

⚙️ C — you can edit this code
Output
Samosa   Rs 30
Idli     Rs 40
Lassi    Rs 25
Total sales: Rs 95

How do you save structs to a file with fwrite and fread in C?

Text files are easy to read for people. Binary files store the raw bytes of your variables, so a whole struct (Lesson 4) can be saved in one call.

fwrite(address, size of one item, count, file) writes items. fread does the opposite and returns how many items it really read. Use modes "wb" and "rb".

A binary file made on one kind of computer may not load correctly on another, because sizes and byte order can differ. For sharing data, text files are safer.

Try it: add a third book and change 2 to 3 in fwrite and the loop.

⚙️ C — you can edit this code
Output
Loaded 2 books
Malgudi Days: 4 copies
Ignited Minds: 2 copies

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

FILE *f = fopen("note.txt", "w");
fprintf(f, "A\n");
fclose(f);
f = fopen("note.txt", "a");
fprintf(f, "B\n");
fclose(f);
f = fopen("note.txt", "w");
fprintf(f, "C\n");
fclose(f);
char line[10];
f = fopen("note.txt", "r");
while (fgets(line, sizeof(line), f) != NULL) {
    printf("%s", line);
}
fclose(f);

Question 2. What does this print?

FILE *f = fopen("nums.txt", "w");
fprintf(f, "10 20 x 30\n");
fclose(f);
f = fopen("nums.txt", "r");
int n, sum = 0;
while (fscanf(f, "%d", &n) == 1) {
    sum += n;
}
fclose(f);
printf("%d\n", sum);

Question 3. homework.txt does not exist. What does this print?

FILE *f = fopen("homework.txt", "r");
if (f == NULL) {
    printf("No file\n");
} else {
    printf("Opened\n");
    fclose(f);
}

🧩 Your challenge

fees.txt has one line per student: name, total fee and amount paid. Read it with fscanf. Write every student who still owes money into due.txt as "name due-amount". Then read due.txt back and print it, followed by the count. Expected output: Aman 6000 Kabir 15000 Students with dues: 2

Expected output :
Aman 6000
Kabir 15000
Students with dues: 2
🗂️ fees.txt — a file your program can open
Riya 15000 15000
Aman 15000 9000
Zoya 15000 15000
Kabir 15000 0
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

FILE f = fopen("marks.txt", "w");
fprintf(f, "Riya 91\n");
fclose(f);

Line 1: error: variable has incomplete type 'FILE' (aka 'struct _IO_FILE')

✅ Right

FILE *f = fopen("marks.txt", "w");
if (f != NULL) {
    fprintf(f, "Riya 91\n");
    fclose(f);
    printf("Saved\n");
}

fopen returns a pointer, FILE *. A FILE is only ever used through a pointer, so forgetting the * is an error. Also check for NULL before using the file.

❌ Wrong

FILE *f = fopen("log.txt", "w");
fprintf(f, "Day 1\nDay 2\n");
fclose(f);
f = fopen("log.txt", "w");
fprintf(f, "Day 3\n");
fclose(f);
char line[20];
f = fopen("log.txt", "r");
while (fgets(line, sizeof(line), f) != NULL) {
    printf("%s", line);
}
fclose(f);

Compiles and runs, but prints: Day 3 ⏎

✅ Right

FILE *f = fopen("log.txt", "w");
fprintf(f, "Day 1\nDay 2\n");
fclose(f);
f = fopen("log.txt", "a");
fprintf(f, "Day 3\n");
fclose(f);
char line[20];
f = fopen("log.txt", "r");
while (fgets(line, sizeof(line), f) != NULL) {
    printf("%s", line);
}
fclose(f);

Opening with "w" again wiped Day 1 and Day 2. To add to a file, open it with "a".

❌ Wrong

FILE *f = fopen("list.txt", "w");
fprintf(f, "Rice\nDal\n");
fclose(f);
char line[20];
int count = 0;
f = fopen("list.txt", "r");
while (!feof(f)) {
    fgets(line, sizeof(line), f);
    count++;
}
fclose(f);
printf("%d lines\n", count);

Compiles and runs, but prints: 3 lines ⏎

✅ Right

FILE *f = fopen("list.txt", "w");
fprintf(f, "Rice\nDal\n");
fclose(f);
char line[20];
int count = 0;
f = fopen("list.txt", "r");
while (fgets(line, sizeof(line), f) != NULL) {
    count++;
}
fclose(f);
printf("%d lines\n", count);

feof becomes true only AFTER a read has failed, so the loop runs one extra time. Use the return value of fgets (or fscanf) to control the loop.

📌 Remember

  • fopen(name, mode) returns a FILE * or NULL; always check for NULL and always fclose.
  • "r" reads, "w" creates or empties, "a" adds to the end; add b for binary files.
  • fprintf writes text; fgets reads a line; fscanf reads words and numbers.
  • Control read loops with the return value of fgets/fscanf, not with feof.
  • fwrite and fread save and load whole structs, but binary files are not portable.

Finished the quiz and the challenge?

Questions students ask

Where does fopen create the file in C?

In the program's current folder, unless you give a full path like "data/marks.txt". In this browser, files live only in the program's own folder while it runs.

What happens if I forget fclose in C?

Data you wrote may still be waiting in a memory buffer and may never reach the file. Most systems also limit how many files can be open at once. Close every file you open.

What is the difference between a text file and a binary file?

A text file stores characters you can read in any editor, like "Riya 91". A binary file stores the raw bytes of variables, which is fast and compact but looks like nonsense in an editor.

Why is while (!feof(f)) wrong in C?

feof only becomes true after a read has already failed. So the loop body runs once more with no new data. Check the value returned by fgets or fscanf instead.