Paramclasses Academy - Blog

Tutorials Details

←
Post 15 of 15

What is File Handling in C Programming

What is File Handling in C Programming

October 14, 2026

1. Introduction to File Handling

In previous modules, we learned about variables, arrays, strings, functions, pointers, structures, and unions. Until now, most of our programs have stored data in variables while the program was running.

But what happens when a program closes? Normally, data stored only in variables is lost.

File handling in C allows us to store data in files and retrieve it later, even after the program has terminated.

For example, file handling is useful for:

  • Saving student records.

  • Creating billing and invoice systems.

  • Storing login information.

  • Generating reports.

  • Reading configuration files.

  • Maintaining product and inventory records.

2. What Is File Handling?

File handling is the process of creating, opening, reading, writing, appending, and closing files using a C program.

C provides standard library functions for file operations through the stdio.h header file.

Common file-handling functions include:

Function

Purpose

fopen()

Opens or creates a file

fclose()

Closes an open file

fprintf()

Writes formatted data to a file

fscanf()

Reads formatted data from a file

fputc()

Writes one character to a file

fgetc()

Reads one character from a file

fputs()

Writes a string to a file

fgets()

Reads a line or string from a file

fread()

Reads binary data

fwrite()

Writes binary data

fseek()

Moves the file position

ftell()

Returns the current file position

rewind()

Moves the file position to the beginning

3. Understanding the FILE Pointer

In C, we use a FILE pointer to work with an open file.

Syntax

FILE *fp;

Here:

  • FILE is a type defined by the C standard library.

  • *fp declares a pointer to a file stream.

  • fp is the variable used to refer to that stream.

A file pointer is used with functions such as fopen(), fprintf(), and fclose().

4. Opening a File Using fopen()

The fopen() function opens a file in a specified mode.

Syntax

FILE *fp = fopen("filename.txt", "mode");

For example:

FILE *fp = fopen("data.txt", "w");

This opens data.txt in write mode. If the file does not exist, it is created. If it already exists, its previous contents are erased.

Important: Always check whether fopen() succeeded. It returns NULL if the file cannot be opened.

5. File Opening Modes

Mode

Description

"r"

Opens an existing file for reading

"w"

Opens for writing; creates or truncates the file

"a"

Opens for appending; creates the file if needed

"r+"

Opens an existing file for reading and writing

"w+"

Opens for reading and writing; creates or truncates the file

"a+"

Opens for reading and appending; creates the file if needed

"rb"

Opens a binary file for reading

"wb"

Opens a binary file for writing

"ab"

Opens a binary file for appending

The b mode character is relevant on systems that distinguish text and binary streams. On some systems, such as Unix-like systems, the distinction has no effect.

6. Writing Data to a File

Let's create a program that writes text to a file.

Example 1: Writing to a File

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "w");

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        return 1;
    }

    fprintf(fp, "Welcome to C Programming!\n");
    fprintf(fp, "This is Module 15.\n");

    fclose(fp);

    printf("Data written successfully.\n");

    return 0;
}

Output

Data written successfully.

The file data.txt will contain:

Welcome to C Programming!
This is Module 15.

Explanation

  1. #include <stdio.h> provides the file-handling functions.

  2. fopen() opens data.txt in write mode.

  3. The if statement checks whether the file was opened successfully.

  4. fprintf() writes formatted text into the file.

  5. fclose() closes the file and completes buffered output.

  6. return 0; indicates successful program termination.

Note: The program's success message appears in the console, while the written text is stored in the file.

7. Reading Data from a File

We can use fgets() to read text from a file one line at a time.

Example 2: Reading a File

This example reads the data.txt file created in the previous example.

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "r");
    char line[100];

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        return 1;
    }

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

    fclose(fp);

    return 0;
}

Output

Welcome to C Programming!
This is Module 15.

Explanation

  • fopen("data.txt", "r") opens the existing file for reading.

  • char line[100] creates a buffer to store a line of text.

  • fgets() reads at most 99 characters plus the terminating null character.

  • The while loop continues until fgets() returns NULL, indicating that no more input was read.

  • fclose() closes the file.

8. Appending Data to a File

Appending means adding new content to the end of a file without deleting its existing contents.

Example 3: Appending Data

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "a");

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        return 1;
    }

    fprintf(fp, "New line added to the file.\n");

    fclose(fp);

    printf("Data appended successfully.\n");

    return 0;
}

Output

Data appended successfully.

The new line is added to the end of data.txt.

Remember: Use "w" when you want to replace the file's contents and "a" when you want to preserve existing contents and add new data.

9. Reading and Writing One Character

C provides fputc() and fgetc() for character-by-character file operations.

Example 4: Writing and Reading a Character

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("char.txt", "w");

    if (fp == NULL)
    {
        printf("Unable to open file.\n");
        return 1;
    }

    fputc('A', fp);
    fclose(fp);

    fp = fopen("char.txt", "r");

    if (fp == NULL)
    {
        printf("Unable to read file.\n");
        return 1;
    }

    int ch = fgetc(fp);

    if (ch != EOF)
    {
        printf("Character: %c\n", ch);
    }

    fclose(fp);

    return 0;
}

Output

Character: A

Notice that fgetc() returns an int, not a char, so that it can represent every possible unsigned character value as well as the special EOF value.

10. Using fscanf() to Read Formatted Data

The fscanf() function reads formatted data from a file.

Suppose student.txt contains:

101 Rahul 85

The following program reads the student's ID, name, and marks.

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("student.txt", "r");
    int id, marks;
    char name[50];

    if (fp == NULL)
    {
        printf("Unable to open file.\n");
        return 1;
    }

    if (fscanf(fp, "%d %49s %d", &id, name, &marks) == 3)
    {
        printf("Student ID: %d\n", id);
        printf("Name: %s\n", name);
        printf("Marks: %d\n", marks);
    }
    else
    {
        printf("Invalid student data.\n");
    }

    fclose(fp);

    return 0;
}

Output

Student ID: 101
Name: Rahul
Marks: 85

The %49s format limits the number of characters read into name to prevent overflowing the 50-character array. This simple format reads a single-word name, not a full name containing spaces.

11. Real-World Project: Student Record Saver

Let's combine file handling with structures to save a student's information.

#include <stdio.h>

struct Student
{
    int id;
    char name[50];
    float marks;
};

int main(void)
{
    struct Student s;
    FILE *fp;

    printf("Enter student ID: ");
    if (scanf("%d", &s.id) != 1)
        return 1;

    printf("Enter student name (one word): ");
    if (scanf("%49s", s.name) != 1)
        return 1;

    printf("Enter marks: ");
    if (scanf("%f", &s.marks) != 1)
        return 1;

    fp = fopen("student_record.txt", "a");

    if (fp == NULL)
    {
        printf("Unable to open file.\n");
        return 1;
    }

    if (fprintf(fp, "%d %s %.2f\n", s.id, s.name, s.marks) < 0)
    {
        printf("Error writing student record.\n");
        fclose(fp);
        return 1;
    }

    if (fclose(fp) == EOF)
    {
        printf("Error closing file.\n");
        return 1;
    }

    printf("Student record saved successfully.\n");

    return 0;
}

Sample Input

Enter student ID: 101
Enter student name (one word): Rahul
Enter marks: 87.5

Output

Student record saved successfully.

The file student_record.txt will contain:

101 Rahul 87.50

Because the program opens the file in append mode, each new student record is added to the end.

12. Common File-Handling Mistakes

  1. Not checking fopen(): A file may not exist, or the program may lack permission to open it.

  2. Using the wrong mode: "w" erases existing contents; use "a" when you need to preserve them.

  3. Forgetting fclose(): Closing files releases resources and ensures buffered output is finalized.

  4. Using a file pointer after closing: Do not perform further file operations through a closed stream.

  5. Incorrect end-of-file checks: Check the return value of fgets(), fscanf(), or fgetc() rather than using while (!feof(fp)).

  6. Buffer overflow: Limit string input to the destination buffer's capacity.

  7. Ignoring write errors: File writes and closing can fail, so important applications should check their return values.

13. Practical Exercises

Try these programs yourself:

  1. Create a file named welcome.txt and write your name and course name into it.

  2. Read and display all lines from a text file.

  3. Append five new lines to an existing file.

  4. Count the characters in a text file.

  5. Save the details of five students in a file.

  6. Create a simple product inventory file that stores product IDs, names, and prices.

  7. Build a program that reads student records and calculates the average marks.

14. Interview Questions

Q1. What is file handling in C?

File handling allows a program to store and retrieve data using files.

Q2. What does fopen() do?

It opens a file and returns a file stream pointer, or NULL if opening fails.

Q3. What is the difference between "w" and "a"?

"w" creates or truncates a file, while "a" adds data to the end of the file.

Q4. Why is fclose() important?

It closes the stream, releases associated resources, and finalizes buffered output.

Q5. What does EOF mean?

EOF is a special negative integer constant used to indicate end-of-file or certain input failures, depending on the function.

Q6. What is the difference between fprintf() and fscanf()?

fprintf() writes formatted data to a file; fscanf() reads formatted data from a file.

Q7. What is the purpose of fgets()?

It reads a line or a bounded amount of text from a file or input stream.

Q8. What is the difference between text and binary files?

Text files represent data as characters, while binary files store data as bytes without requiring a text representation.

15. Quick Revision

  • FILE *fp declares a file stream pointer.

  • fopen() opens a file.

  • fclose() closes a file.

  • fprintf() writes formatted text.

  • fscanf() reads formatted data.

  • fgets() reads a bounded line of text.

  • fgetc() reads a character.

  • fputc() writes a character.

  • "r" reads, "w" writes, and "a" appends.

  • Always check file-opening and important file-operation results.

16. Homework

Build a Student Management System using File Handling with these features:

  • Add a student record.

  • Display saved student records.

  • Append new records without deleting existing ones.

  • Store student ID, name, and marks.

  • Handle file-opening errors correctly.

Try to complete the project using structures, functions, and file handling together.

Conclusion

Congratulations! You have completed Module 15: File Handling in C Programming. You now know how to open, read, write, append, and close files, and how to save records permanently using C.

←
Post 15 of 15