Skip to content

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.

Beginner 20 min read·Lesson 31 of 37 in C Programming

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 type FILE * from <stdio.h>. fopen associates a stream with a named file in a given mode; input/output functions read and write through the stream; fclose flushes 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

ModeMeaningIf file existsIf missing
"r"readread from startfails (NULL)
"w"writetruncated to emptycreated
"a"appendwrite at endcreated
"r+"read and writefrom startfails
"w+"read and writetruncatedcreated
add bbinary ("rb", "wb")no newline translation

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

C
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { perror("data.txt"); return 1; }
fprintf(fp, "%d %s\n", id, name);
fclose(fp);
fp = fopen("data.txt", "r");
char line[128];
while (fgets(line, sizeof line, fp) != NULL) { /* process line */ }
fclose(fp);
  • Never use feof as 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

C
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "w");
if (!fp) { perror("notes.txt"); return 1; }
fprintf(fp, "Arrays\nPointers\nStructures\n");
fclose(fp);
fp = fopen("notes.txt", "r");
if (!fp) { perror("notes.txt"); return 1; }
char line[64];
int n = 0;
while (fgets(line, sizeof line, fp))
printf("%d: %s", ++n, line);
fclose(fp);
return 0;
}
Output
1: Arrays
2: Pointers
3: Structures

Handling a missing file

C
#include <stdio.h>
int main(void) {
FILE *fp = fopen("does-not-exist.txt", "r");
if (fp == NULL) {
printf("could not open file\n");
return 0;
}
fclose(fp);
return 0;
}
Output
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

C
#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char name[20];
double price;
} Item;
int main(void) {
Item stock[] = {{1, "Pen", 10.0}, {2, "Notebook", 45.5}, {3, "Stapler", 120.0}};
FILE *fp = fopen("items.dat", "wb");
if (!fp) return 1;
size_t written = fwrite(stock, sizeof stock[0], 3, fp);
fclose(fp);
printf("wrote %zu records\n", written);
fp = fopen("items.dat", "rb+");
if (!fp) return 1;
fseek(fp, 0, SEEK_END);
long bytes = ftell(fp);
printf("file is %ld bytes = %ld records\n", bytes, bytes / (long)sizeof(Item));
Item it;
fseek(fp, 1 * (long)sizeof(Item), SEEK_SET); /* jump to record #2 */
fread(&it, sizeof it, 1, fp);
printf("record 2: %s %.2f\n", it.name, it.price);
it.price = 39.99; /* update in place */
fseek(fp, 1 * (long)sizeof(Item), SEEK_SET);
fwrite(&it, sizeof it, 1, fp);
rewind(fp);
while (fread(&it, sizeof it, 1, fp) == 1)
printf("%d %-9s %7.2f\n", it.id, it.name, it.price);
fclose(fp);
return 0;
}
Output
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 ftell gives the file size: 3 records × 32 bytes each on this platform.
  • Record n (0-based) starts at byte n * sizeof(Item), so fseek jumps straight to the second record.
  • Writing at the same offset updates the record in place; rewind then re-reads every record.
  • fread returns 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:

TextOutput
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

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

FILE *fp = fopen("in.txt", "r");
fgets(buf, sizeof buf, fp);

Prefer

FILE *fp = fopen("in.txt", "r");
if (!fp) { perror("in.txt"); return 1; }
fgets(buf, sizeof buf, fp);

If the file is missing, fp is NULL and the read crashes.

Looping on feof

Avoid

while (!feof(fp)) {
fgets(line, sizeof line, fp);
printf("%s", line);
}

Prefer

while (fgets(line, sizeof line, fp)) {
printf("%s", line);
}

feof becomes true only after a read fails, so the last line is processed twice.

Opening with "w" to update

Avoid

FILE *fp = fopen("contacts.txt", "w"); /* erases everything */

Prefer

FILE *fp = fopen("contacts.txt", "a"); /* adds to the end */

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.
  • fseek with offsets other than 0 or a value from ftell is not portable on text streams; use binary mode for random access.

Key takeaways

  • fopen with a mode; check for NULL; fclose when done.
  • Read text with while (fgets(...)), never while (!feof(...)).
  • fwrite/fread plus fseek give random access to binary records.

Try it yourself

  1. 1
    Write a program that counts the lines, words and characters in a text file (like the Unix wc command).
  2. 2
    Copy 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?
Practise this topic