File Handling in C
Every program so far forgot everything the moment it ended. Marks you typed, records you sorted: all gone. That's because variables live in RAM, which is temporary. To keep data after the program closes, you must save it in a file on the disk.
In this lesson you will learn what file handling is, how C talks to files through a FILE pointer, the difference between text and binary files, and the three steps of every file program: open, use, close.
What You Will Learn
- Why file handling is needed.
- What a FILE pointer is.
- Text files vs binary files.
- The open → read/write → close steps.
- The main file functions at a glance.
- Your first program that writes and reads a file.
What is File Handling in C?
Exam definition: File handling is the process of creating, opening, reading, writing and closing files on secondary storage using library functions from <stdio.h>. It lets data be stored permanently, beyond the life of the program.
Memory trick: RAM is a whiteboard: quick to use, wiped when class ends. A file is a notebook: slower, but it keeps your notes. File handling = open the notebook, write/read, close it so the pages don't fly away.
Why do we need files?
- Permanent storage: data survives after the program ends or the computer restarts.
- Large data: files can hold far more than fits comfortably in memory.
- No retyping: read input from a file instead of typing it every run.
- Sharing: one program writes a file, another reads it (reports, logs, CSV).
The FILE Pointer
C doesn't let you touch the disk directly. Instead, fopen gives you a pointer to a FILE structure (defined in stdio.h) that keeps track of the file: where it is, the current position, a memory buffer, and error flags. Every file function takes this pointer.
FILE *fp; /* file pointer */
fp = fopen("marks.txt", "w"); /* open for writing */
fprintf(fp, "%d\n", 95); /* write through fp */
fclose(fp); /* close */
Your program FILE structure (buffer) Disk
fprintf(fp, ...) --> [ data collected here ] --> marks.txt
written to disk when the buffer
is full, or at fclose / fflush
This buffer is why fclose matters: unsaved data in the buffer is written to disk only when the file is flushed or closed.
Text Files vs Binary Files
| Point | Text file | Binary file |
|---|---|---|
| Stores data as | Readable characters | Raw bytes (as in memory) |
| Open in Notepad | Readable | Looks like junk |
| Example: number 12345 | 5 characters '1' '2' '3' '4' '5' | 4 bytes (one int) |
| Functions | fprintf, fscanf, fgets, fputs, fgetc, fputc | fwrite, fread |
| Mode letters | "r", "w", "a" | "rb", "wb", "ab" |
| Examples | .txt, .csv, .c | .jpg, .exe, .dat |
Syntax: Steps and Main Functions
1. DECLARE FILE *fp;
2. OPEN fp = fopen("name", "mode");
3. CHECK if (fp == NULL) { error }
4. USE fprintf / fscanf / fgets / fputs / fread / fwrite ...
5. CLOSE fclose(fp);
| Function | Job |
|---|---|
fopen / fclose | Open / close a file |
fprintf / fscanf | Formatted write / read (like printf/scanf) |
fputc / fgetc | Write / read one character |
fputs / fgets | Write / read one line (string) |
fwrite / fread | Write / read blocks of bytes (binary) |
fseek / ftell / rewind | Move / report / reset the position |
feof / ferror | Check for end of file / error |
remove / rename | Delete / rename a file |
Example 1: Write a File, Then Read It Back
#include <stdio.h>
int main(void)
{
FILE *fp;
char line[100];
/* write */
fp = fopen("notes.txt", "w");
if (fp == NULL)
{
printf("Cannot create file\n");
return 1;
}
fprintf(fp, "C was created by Dennis Ritchie.\n");
fprintf(fp, "It was developed in %d.\n", 1972);
fclose(fp);
printf("File written.\n");
/* read */
fp = fopen("notes.txt", "r");
if (fp == NULL)
{
printf("Cannot open file\n");
return 1;
}
printf("File contents:\n");
while (fgets(line, sizeof(line), fp) != NULL)
printf(" %s", line);
fclose(fp);
remove("notes.txt"); /* clean up the demo file */
return 0;
}
Output
File written. File contents: C was created by Dennis Ritchie. It was developed in 1972.
Code Explanation
fopen("notes.txt", "w")creates the file (or empties it if it exists) and returns a FILE pointer.- Checking for
NULLcatches problems like a missing folder or no permission. fprintf(fp, ...)works exactly like printf, but writes into the file.fclose(fp)flushes the buffer to disk and releases the file.- Reopening with
"r"and callingfgetsin a loop reads one line at a time until it returns NULL (end of file). removedeletes the demo file. In a real program, you'd keep it.
How Standard Streams Fit In
Your keyboard and screen are also "files" to C. Three FILE pointers are always open:
| Stream | Means | Same as |
|---|---|---|
stdin | Standard input (keyboard) | scanf(...) = fscanf(stdin, ...) |
stdout | Standard output (screen) | printf(...) = fprintf(stdout, ...) |
stderr | Standard error (screen, unbuffered) | For error messages |
Example 2: Saving Student Records to a File
#include <stdio.h>
struct student
{
int roll;
char name[20];
int marks;
};
int main(void)
{
struct student s[3] = { {1, "Asha", 88}, {2, "Ravi", 72}, {3, "Neha", 95} };
struct student r;
FILE *fp = fopen("students.txt", "w");
int i, count = 0, total = 0;
if (fp == NULL)
return 1;
for (i = 0; i < 3; i++)
fprintf(fp, "%d %s %d\n", s[i].roll, s[i].name, s[i].marks);
fclose(fp);
fp = fopen("students.txt", "r");
if (fp == NULL)
return 1;
while (fscanf(fp, "%d %19s %d", &r.roll, r.name, &r.marks) == 3)
{
printf("Read: %d %-5s %d\n", r.roll, r.name, r.marks);
count++;
total += r.marks;
}
fclose(fp);
printf("%d records, average %.2f\n", count, (float) total / count);
remove("students.txt");
return 0;
}
Output
Read: 1 Asha 88 Read: 2 Ravi 72 Read: 3 Neha 95 3 records, average 85.00
- Each record is written as one line:
1 Asha 88. You could open students.txt in Notepad and read it. fscanfreturns the number of items read. The loop continues while it reads all 3; at the end of the file it returns less (EOF), and the loop stops.
Practice: C program to write and read a text file.
Important Points to Remember
- Files store data permanently; variables don't.
- All file functions are in <stdio.h> and use a FILE *.
- Steps: declare → open → check NULL → use → close.
- Text files are human-readable; binary files store raw bytes.
- fclose flushes the buffer: data may be lost without it.
- stdin, stdout and stderr are always-open streams.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Not checking fopen for NULL | Crash on the next file call | if (fp == NULL) |
Forgetting fclose | Data may not be saved; file stays locked | Always close |
Opening with "w" when you meant to add | Old contents erased | Use "a" (append) |
Using printf instead of fprintf(fp, ...) | Text goes to the screen, not the file | Pass the file pointer |
Windows path "C:\new\data.txt" | \n becomes a newline | "C:\\new\\data.txt" or "C:/new/data.txt" |
File Handling Practice Questions
- Why is file handling needed in C?
- What is a FILE pointer?
- Give three differences between text and binary files.
- List the steps of a file program.
- What are stdin, stdout and stderr?
Show answers
- To store data permanently, handle large data, avoid retyping input, and share data between programs.
- A pointer to a FILE structure (from stdio.h) that holds information about an open file; all file functions use it.
- Text stores readable characters, binary stores raw bytes; text uses fprintf/fscanf, binary uses fwrite/fread; text is readable in an editor, binary isn't (also: binary is usually smaller).
- Declare a FILE pointer, open with fopen, check for NULL, read/write, close with fclose.
- The three standard streams: keyboard input, screen output and error output, always open.
Coding Exercise
Write the multiplication table of 9 (9 × 1 to 9 × 5) to a file named table.txt, then read the file and print it on the screen.
Show solution
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("table.txt", "w");
char line[50];
int i;
if (fp == NULL)
return 1;
for (i = 1; i <= 5; i++)
fprintf(fp, "9 x %d = %d\n", i, 9 * i);
fclose(fp);
fp = fopen("table.txt", "r");
if (fp == NULL)
return 1;
while (fgets(line, sizeof(line), fp) != NULL)
printf("%s", line);
fclose(fp);
remove("table.txt");
return 0;
}
9 x 1 = 9 9 x 2 = 18 9 x 3 = 27 9 x 4 = 36 9 x 5 = 45
Quick Quiz: File Handling in C (MCQ)
-
File handling functions are declared in:
A)
stdlib.hB)stdio.hC)file.hD)string.h -
A file pointer is declared as:
A)
file *fp;B)FILE *fp;C)File fp;D)FILE fp[]; -
fopen returns what on failure?
A) 0 bytes B) −1 C) NULL D) EOF
-
Which function writes formatted text to a file?
A)
printfB)fprintfC)fscanfD)fread -
Which file type is human-readable?
A) Binary B) Text C) Both D) Neither
Show answers
- B:
stdio.h. - B:
FILE *fp; - C: NULL.
- B:
fprintf. - B: text.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| File handling | Store data permanently on disk |
|---|---|
| Header | <stdio.h> |
| File pointer | FILE *fp; |
| Steps | Open → check NULL → use → close |
| Text file | Readable characters: fprintf, fscanf, fgets |
| Binary file | Raw bytes: fwrite, fread |
| Standard streams | stdin, stdout, stderr |
Frequently asked questions
- What is file handling in C?
- Creating, opening, reading, writing and closing files with stdio.h functions so data is stored permanently.
- What is the difference between text and binary files?
- Text files store readable characters; binary files store raw bytes exactly as in memory.
- Why must you call fclose?
- It flushes the buffer to disk and releases the file; without it data can be lost.
Remember
- RAM = whiteboard, file = notebook.
- Open, use, close: every time.
Next Topic
Next lesson: Opening and Closing Files in C. You will learn every fopen() mode (r, w, a, r+, w+, a+) and how to close files properly.