🔴 Advanced  ·  Lesson 36

File Handling in C

What is file handling?

Normally, everything a C program stores in variables vanishes the moment the program ends. File handling lets a program save data to a file on disk so it survives — you can write it now and read it back tomorrow. This is how programs remember scores, settings, records and reports.

C does all of this through a special FILE pointer and a set of functions in <stdio.h>. The pattern is always the same: open a file, use it, close it.

The FILE pointer and fopen

To work with a file, you first open it with fopen, which gives you back a FILE pointer. Every later operation uses that pointer.

C Language
FILE *fp;                       // a file pointer
fp = fopen("data.txt", "w");    // open for writing

if (fp == NULL) {               // opening can fail!
    printf("Could not open file.\n");
    return 1;
}

The fopen call takes two things: the file name and a mode that says what you want to do with it.

File opening modes

ModeMeaning
"r"Read only — the file must already exist
"w"Write — creates a new file or erases an existing one
"a"Append — adds to the end, keeping old content
"r+"Read and write an existing file
"w+"Read and write; erases existing content
⚠️ Careful with "w"

Opening an existing file in "w" mode erases everything in it immediately. Use "a" when you want to keep the old data.

Writing to a file

Once open in a write mode, fprintf works just like printf but sends text into the file.

C Language
#include <stdio.h>
int main() {
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL) return 1;

    fprintf(fp, "Hello, file!\n");
    fprintf(fp, "Marks: %d\n", 95);

    fclose(fp);                 // save and close
    printf("Data written.\n");
    return 0;
}
Output (on screen):
Data written.

Inside data.txt:
Hello, file!
Marks: 95

Reading from a file

To read, open the file in "r" mode and use fgets (for lines) or fscanf (for formatted values).

C Language
#include <stdio.h>
int main() {
    FILE *fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("File not found.\n");
        return 1;
    }
    char line[100];
    while (fgets(line, sizeof(line), fp) != NULL)
        printf("%s", line);      // print each line

    fclose(fp);
    return 0;
}
Output:
Hello, file!
Marks: 95

The fgets loop keeps reading until it returns NULL, which marks the end of the file.

Always check and close

Two habits make file handling safe and reliable:

  • Check for NULL right after fopen — the file may be missing or locked.
  • Call fclose when done — it flushes buffered data to disk and frees the file.
💡 Why fclose matters

Text you write is often held in a buffer first. fclose (or fflush) is what actually pushes it into the file. Skip it and you can lose the last part of your data.

Common mistakes

  • Using the FILE pointer without checking it for NULL first.
  • Opening an existing file in "w" and accidentally erasing it.
  • Forgetting fclose, which can lose buffered data.
  • Trying to read a file opened in write mode, or write to one opened as read-only.
🏋️ Practice

Write a program that appends a new line to log.txt each time it runs (mode "a"), then a second program that reads and prints the whole log. Run the first one three times and confirm the log grows.

Summary

  • File handling saves data permanently using a FILE pointer and stdio.h functions.
  • Open with fopen(name, mode); always check the result for NULL.
  • Modes: "r" read, "w" overwrite, "a" append, and the + variants.
  • Write with fprintf; read with fgets or fscanf.
  • Always fclose to flush data and release the file.

Frequently Asked Questions

What is file handling in C?
File handling is the ability of a C program to create, write to, read from and close files on disk, so data is saved permanently instead of disappearing when the program ends. It uses a FILE pointer and functions from stdio.h such as fopen, fprintf, fscanf and fclose.
What is the FILE pointer in C?
The FILE pointer is a special pointer that represents an open file. When you call fopen, it returns a FILE * that you then pass to every read, write and close function so C knows which file you mean. If fopen fails, it returns NULL.
What is the difference between "w" and "a" mode in fopen?
Mode "w" opens a file for writing and erases any existing contents, so you start with an empty file. Mode "a" (append) also writes, but it keeps the existing contents and adds new data at the end. Use "w" to overwrite and "a" to add without losing old data.
Why should I always check if fopen returned NULL?
Because opening a file can fail — the file might not exist, or you may lack permission. If fopen returns NULL and you use that pointer anyway, the program crashes. Checking for NULL right after opening lets you handle the error safely.
What happens if I forget to call fclose?
Data you wrote may stay in a buffer and never actually reach the file, and the file stays locked and its resources reserved. Calling fclose flushes buffered data to disk and releases the file, so forgetting it can lose data or leak resources.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.