Skip to content
StudyFame

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

PointText fileBinary file
Stores data asReadable charactersRaw bytes (as in memory)
Open in NotepadReadableLooks like junk
Example: number 123455 characters '1' '2' '3' '4' '5'4 bytes (one int)
Functionsfprintf, fscanf, fgets, fputs, fgetc, fputcfwrite, 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);
FunctionJob
fopen / fcloseOpen / close a file
fprintf / fscanfFormatted write / read (like printf/scanf)
fputc / fgetcWrite / read one character
fputs / fgetsWrite / read one line (string)
fwrite / freadWrite / read blocks of bytes (binary)
fseek / ftell / rewindMove / report / reset the position
feof / ferrorCheck for end of file / error
remove / renameDelete / 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

  1. fopen("notes.txt", "w") creates the file (or empties it if it exists) and returns a FILE pointer.
  2. Checking for NULL catches problems like a missing folder or no permission.
  3. fprintf(fp, ...) works exactly like printf, but writes into the file.
  4. fclose(fp) flushes the buffer to disk and releases the file.
  5. Reopening with "r" and calling fgets in a loop reads one line at a time until it returns NULL (end of file).
  6. remove deletes 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:

StreamMeansSame as
stdinStandard input (keyboard)scanf(...) = fscanf(stdin, ...)
stdoutStandard output (screen)printf(...) = fprintf(stdout, ...)
stderrStandard 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.
  • fscanf returns 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

MistakeWhat happensFix
Not checking fopen for NULLCrash on the next file callif (fp == NULL)
Forgetting fcloseData may not be saved; file stays lockedAlways close
Opening with "w" when you meant to addOld contents erasedUse "a" (append)
Using printf instead of fprintf(fp, ...)Text goes to the screen, not the filePass 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

  1. Why is file handling needed in C?
  2. What is a FILE pointer?
  3. Give three differences between text and binary files.
  4. List the steps of a file program.
  5. What are stdin, stdout and stderr?
Show answers
  1. To store data permanently, handle large data, avoid retyping input, and share data between programs.
  2. A pointer to a FILE structure (from stdio.h) that holds information about an open file; all file functions use it.
  3. 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).
  4. Declare a FILE pointer, open with fopen, check for NULL, read/write, close with fclose.
  5. 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)

  1. File handling functions are declared in:

    A) stdlib.h   B) stdio.h   C) file.h   D) string.h

  2. A file pointer is declared as:

    A) file *fp;   B) FILE *fp;   C) File fp;   D) FILE fp[];

  3. fopen returns what on failure?

    A) 0 bytes   B) −1   C) NULL   D) EOF

  4. Which function writes formatted text to a file?

    A) printf   B) fprintf   C) fscanf   D) fread

  5. Which file type is human-readable?

    A) Binary   B) Text   C) Both   D) Neither

Show answers
  1. B: stdio.h.
  2. B: FILE *fp;
  3. C: NULL.
  4. B: fprintf.
  5. B: text.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

File handlingStore data permanently on disk
Header<stdio.h>
File pointerFILE *fp;
StepsOpen → check NULL → use → close
Text fileReadable characters: fprintf, fscanf, fgets
Binary fileRaw bytes: fwrite, fread
Standard streamsstdin, 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.