File Handling in C Programming: Learn File Operations with Easy Examples | Complete Tutorial for Beginners with Programs

⬅ Previous Chapter | Current Chapter: Structures and Unions | Next Chapter ➜

Author: Mujtaba Ansari

File Handling in C Programming: Complete Guide with Syntax, Functions, Examples & Programs

Want to store, read, and manage data beyond your program’s runtime? Learn File Handling in C and discover how files make your programs more powerful and practical.

In C programming, data stored in variables is generally available only while the program is running. Once the program ends, that data is lost. File Handling provides a way to store data permanently in files so that it can be accessed and processed later.

In this complete guide, you will learn File Handling in C, file types, file opening modes, important file functions, sequential and random access, and practical C programs with examples.

Key Benefits:

  • Store data permanently
  • Read and write files easily
  • Update and manage existing data
  • Handle large amounts of information
  • Build practical, real-world C applications

A file is a collection of data stored on a storage device such as a hard disk, SSD, or other secondary storage.

File Handling in C is the process of creating, opening, reading, writing, updating, appending, and closing files using C programs.

Unlike temporary data stored in variables, data written to a file can remain available even after the program terminates. This is known as persistent data storage.

File Handling is useful when a program needs to:

  • Store data permanently
  • Read previously stored information
  • Add new data to an existing file
  • Update or process stored records
  • Manage large amounts of information
  • Transfer or copy data between files
  • Build practical applications such as student records, billing systems, employee databases, and inventory systems

C provides several functions through the standard <stdio.h> library for working with files.

FunctionPurpose
fopen()Opens or creates a file
fclose()Closes an opened file
fgetc()Reads a single character from a file
fputc()Writes a single character to a file
fprintf()Writes formatted data to a file
fscanf()Reads formatted data from a file
fread()Reads blocks of binary data
fwrite()Writes blocks of binary data
fseek()Moves the file position indicator
ftell()Returns the current file position
rewind()Moves the file position to the beginning
feof()Checks whether the end of a file has been reached

Note: Older C textbooks sometimes discuss getw() and putw(). They are not part of the modern standard C approach and are generally better avoided in new programs. Use fread(), fwrite(), fprintf(), and fscanf() according to the type of data being processed.

Before performing file operations, we generally use a file pointer.

Syntax
FILE *fp;

Here:

  • FILE is a type defined in <stdio.h>.
  • fp is a file pointer.
  • The pointer is used by C file functions to work with the opened file.

For example:

FILE *fp;

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

The fopen() function is used to open an existing file or create a new file depending on the selected mode.

Syntax
FILE *fopen(const char *filename, const char *mode);

Example:

FILE *fp;

fp = fopen("student.txt", "w");

If the file cannot be opened, fopen() returns NULL.

Therefore, it is good practice to check the file pointer:

if (fp == NULL)
{
    printf("Unable to open the file.");
}

The mode tells C what operation you want to perform on the file.

ModeDescription
"r"Opens an existing file for reading
"w"Opens a file for writing; creates a new file or overwrites an existing file
"a"Opens a file for appending data at the end
"r+"Opens an existing file for reading and writing
"w+"Opens a file for reading and writing; existing contents are overwritten
"a+"Opens a file for reading and appending

For binary files, b can be added:

"rb"
"wb"
"ab"
"rb+"
"wb+"
"ab+"

After completing file operations, the file should be closed using fclose().

Syntax
fclose(fp);

Example:

FILE *fp;

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

if (fp != NULL)
{
    /* File operations */
    fclose(fp);
}

Closing a file helps ensure that buffered data is properly written and releases the associated resources.

Important: The correct function name is fclose(), not fclosed().

The fgetc() function reads one character at a time from a file.

Syntax
ch = fgetc(fp);

A common pattern for reading until the end of a file is:

int ch;

while ((ch = fgetc(fp)) != EOF)
{
    putchar(ch);
}
Why use int instead of char?

fgetc() returns either the character read or the special value EOF. Therefore, the receiving variable should normally be declared as int.

The fputc() function writes one character to a file.

Syntax
fputc(ch, fp);

Example:

FILE *fp;

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

if (fp != NULL)
{
    fputc('A', fp);
    fclose(fp);
}

fprintf() works similarly to printf(), but instead of displaying the formatted output on the screen, it writes it to a file.

Syntax
fprintf(fp, "format", values);

Example:

fprintf(fp, "Name: %s\nAge: %d\n", name, age);

This is useful for storing structured text data.

fscanf() reads formatted data from a file.

Syntax
fscanf(fp, "format", &variables);

Example:

fscanf(fp, "%d %s", &roll, name);

It is particularly useful when the file contains data in a predictable format.

The following program creates stud.txt, accepts student names from the user, and then displays the contents of the file.

#include <stdio.h>

int main(void)
{
    FILE *fp;
    int ch;

    fp = fopen("stud.txt", "w");

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

    printf("Enter student names.\n");
    printf("Press Ctrl+D on Linux/macOS or Ctrl+Z followed by Enter on Windows to finish.\n");

    while ((ch = getchar()) != EOF)
    {
        fputc(ch, fp);
    }

    fclose(fp);

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

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

    printf("\nContents of stud.txt:\n");

    while ((ch = fgetc(fp)) != EOF)
    {
        putchar(ch);
    }

    fclose(fp);

    return 0;
}

How this program works

  1. The file stud.txt is opened in "w" mode.
  2. Student names are entered from the keyboard.
  3. fputc() writes the characters to the file.
  4. The file is closed.
  5. The same file is opened in "r" mode.
  6. fgetc() reads the contents character by character.
  7. putchar() displays the contents on the screen.
  8. Finally, the file is closed.

This program reads stud.txt and counts the total uppercase and lowercase letters.

#include <stdio.h>

int main(void)
{
    FILE *fp;
    int ch;
    int uppercase = 0;
    int lowercase = 0;

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

    if (fp == NULL)
    {
        printf("File does not exist or cannot be opened.\n");
        return 1;
    }

    printf("Contents of stud.txt:\n");

    while ((ch = fgetc(fp)) != EOF)
    {
        putchar(ch);

        if (ch >= 'A' && ch <= 'Z')
        {
            uppercase++;
        }
        else if (ch >= 'a' && ch <= 'z')
        {
            lowercase++;
        }
    }

    printf("\n\nTotal uppercase letters = %d\n", uppercase);
    printf("Total lowercase letters = %d\n", lowercase);

    fclose(fp);

    return 0;
}
Example Output
Contents of stud.txt:
Rahul
AMIT
Neha

Total uppercase letters = 5
Total lowercase letters = 9

The exact count depends on the contents of the file.

File Handling can also be used to copy the contents of one file into another.

The following program copies stud.txt into copy.txt.

#include <stdio.h>

int main(void)
{
    FILE *source;
    FILE *destination;
    int ch;

    source = fopen("stud.txt", "r");

    if (source == NULL)
    {
        printf("Source file cannot be opened.\n");
        return 1;
    }

    destination = fopen("copy.txt", "w");

    if (destination == NULL)
    {
        printf("Destination file cannot be created.\n");
        fclose(source);
        return 1;
    }

    while ((ch = fgetc(source)) != EOF)
    {
        fputc(ch, destination);
    }

    fclose(source);
    fclose(destination);

    printf("File copied successfully.\n");

    return 0;
}

Key Concept

Here:

  • source points to stud.txt.
  • destination points to copy.txt.
  • fgetc() reads each character.
  • fputc() writes each character into the destination file.

The following program accepts numbers, stores them in numbers.txt, and then separates them into even.txt and odd.txt.

#include <stdio.h>

int main(void)
{
    FILE *input;
    FILE *evenFile;
    FILE *oddFile;
    int number;

    input = fopen("numbers.txt", "w");

    if (input == NULL)
    {
        printf("Unable to create numbers.txt\n");
        return 1;
    }

    printf("Enter numbers (enter 0 to stop):\n");

    while (1)
    {
        scanf("%d", &number);

        if (number == 0)
        {
            break;
        }

        fprintf(input, "%d\n", number);
    }

    fclose(input);

    input = fopen("numbers.txt", "r");
    evenFile = fopen("even.txt", "w");
    oddFile = fopen("odd.txt", "w");

    if (input == NULL || evenFile == NULL || oddFile == NULL)
    {
        printf("Error opening files.\n");

        if (input != NULL)
            fclose(input);

        if (evenFile != NULL)
            fclose(evenFile);

        if (oddFile != NULL)
            fclose(oddFile);

        return 1;
    }

    while (fscanf(input, "%d", &number) == 1)
    {
        if (number % 2 == 0)
        {
            fprintf(evenFile, "%d\n", number);
        }
        else
        {
            fprintf(oddFile, "%d\n", number);
        }
    }

    fclose(input);
    fclose(evenFile);
    fclose(oddFile);

    printf("Even and odd numbers have been stored successfully.\n");

    return 0;
}

Why this version is better

The original notes used getw() and putw(). For a modern C tutorial, using fprintf() and fscanf() makes the example easier to understand and avoids relying on older/non-standard functions.

File Handling becomes especially useful when working with structures.

For example, a student record can contain:

  • Roll number
  • Name
  • Marks

A structure can group these values together.

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

The following program stores five student records in a text file and then reads them back.

#include <stdio.h>

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

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

    fp = fopen("student_records.txt", "w");

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

    for (i = 1; i <= 5; i++)
    {
        printf("\nEnter details of Student %d\n", i);

        printf("Roll Number: ");
        scanf("%d", &student.roll);

        printf("Name: ");
        scanf("%49s", student.name);

        printf("Marks: ");
        scanf("%f", &student.marks);

        fprintf(fp, "%d %s %.2f\n",
                student.roll,
                student.name,
                student.marks);
    }

    fclose(fp);

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

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

    printf("\n--- Student Records ---\n");

    while (fscanf(fp, "%d %49s %f",
                  &student.roll,
                  student.name,
                  &student.marks) == 3)
    {
        printf("\nRoll Number: %d", student.roll);
        printf("\nName: %s", student.name);
        printf("\nMarks: %.2f\n", student.marks);
    }

    fclose(fp);

    return 0;
}

Note: scanf("%49s", student.name) reads a single-word name. If you want to accept names containing spaces, such as Rahul Kumar, a different input approach such as fgets() should be used.

In sequential access, data is generally processed from the beginning of the file toward the required position.

For example, if you want to read the fifth record, the program normally processes the earlier records first.

Functions such as:

fgetc()
fscanf()

are commonly used for sequential reading.

Example
Record 1 → Record 2 → Record 3 → Record 4 → Record 5

This approach is simple and useful for many text-file operations.

Random access allows the file position indicator to be moved directly to a particular location in a file.

Instead of always starting from the beginning, a program can move the file position using functions such as:

  • fseek()
  • ftell()
  • rewind()

This can be useful when working with files where specific positions need to be accessed.

The fseek() function changes the current position of the file position indicator.

Syntax
fseek(fp, offset, origin);

Where:

  • fp = file pointer
  • offset = number of bytes to move
  • origin = reference position

The standard constants used for origin are:

SEEK_SET
SEEK_CUR
SEEK_END

They represent:

ConstantMeaning
SEEK_SETBeginning of the file
SEEK_CURCurrent position
SEEK_ENDEnd of the file
Example
fseek(fp, 50L, SEEK_SET);

This moves the file position to an offset of 50 bytes from the beginning.

Another example:

fseek(fp, -7L, SEEK_CUR);

This attempts to move the position 7 bytes backward from the current position.

Important: The meaning of byte offsets can be more complicated for text streams. For portable random access, binary files are generally easier to reason about.

The ftell() function returns the current position of the file position indicator.

Syntax
long position;

position = ftell(fp);
Example
#include <stdio.h>

int main(void)
{
    FILE *fp;
    long position;

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

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

    fseek(fp, 50L, SEEK_SET);

    position = ftell(fp);

    printf("Current file position: %ld\n", position);

    fclose(fp);

    return 0;
}

The rewind() function moves the file position indicator back to the beginning of the file.

Syntax
rewind(fp);

It is conceptually similar to:

fseek(fp, 0L, SEEK_SET);
Example
rewind(fp);

After this statement, reading from the file starts again from the beginning.

C programs can work with both text files and binary files.

A text file stores information in a form that can generally be viewed using a text editor.

Examples:

students.txt
employees.csv
data.txt

Functions such as:

fprintf()
fscanf()
fgetc()
fputc()

are commonly used with text files.

Binary files store data as bytes rather than human-readable text.

Functions such as:

fread()
fwrite()

are commonly used for binary data.

Example:

fwrite(&student, sizeof(student), 1, fp);

and:

fread(&student, sizeof(student), 1, fp);

Binary files can be useful when storing structures or other data in a compact machine-readable format.

A simple binary-file example:

#include <stdio.h>

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

int main(void)
{
    FILE *fp;
    struct Student student = {101, "Zain", 85.5};

    fp = fopen("student.dat", "wb");

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

    fwrite(&student, sizeof(student), 1, fp);

    fclose(fp);

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

    return 0;
}

Here, fwrite() writes the structure directly to the binary file.

While working with files in C, keep these points in mind:

  1. Always include the <stdio.h> header.
  2. Declare a file pointer using FILE *.
  3. Use fopen() to open or create a file.
  4. Always check whether fopen() returned NULL.
  5. Select the correct file mode.
  6. Use fgetc() and fputc() for character-based operations.
  7. Use fprintf() and fscanf() for formatted text data.
  8. Use fread() and fwrite() for binary data.
  9. Close files using fclose() after completing operations.
  10. Use fseek(), ftell(), and rewind() when file-position control is required.
  11. Use int when storing the result of fgetc() because it must be able to represent EOF.
  12. Be careful with "w" mode because it can overwrite an existing file.

Beginners often make these mistakes:

1. Using fclosed() Instead of fclose()

Incorrect:

fclosed(fp);

Correct:

fclose(fp);

2. Not Checking fopen()

Always check:

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

3. Using char for fgetc() Result

Avoid:

char ch;

while ((ch = fgetc(fp)) != EOF)

Prefer:

int ch;

while ((ch = fgetc(fp)) != EOF)

4. Forgetting to Close the File

Always close the file after use:

fclose(fp);

5. Accidentally Overwriting a File

Opening a file using:

fopen("data.txt", "w");

can erase the previous contents.

If you want to add data at the end, use:

fopen("data.txt", "a");
Normal VariableFile
Usually stores temporary program dataStores data persistently
Data generally exists during program executionData remains after program termination
Suitable for temporary calculationsSuitable for permanent records
Limited by program memoryCan store much larger datasets
Data is lost when the program ends unless saved elsewhereData can be reopened and processed later

File Handling is an important concept because many real-world programs need persistent data.

Examples include:

  • Student Management Systems
  • Employee Management Systems
  • Library Management Systems
  • Billing Software
  • Inventory Management Systems
  • Banking Applications
  • Customer Record Systems
  • Result Management Systems
  • Log Files
  • Configuration Files
  • Data Export and Import Systems

What is File Handling in C?

File Handling in C is the process of creating, opening, reading, writing, updating, and closing files using C programming functions.

Which header file is used for File Handling in C?

The standard <stdio.h> header provides the main file-handling functions.

What is a file pointer?

A file pointer is a pointer of type FILE * used to access and perform operations on an opened file.

Example:

FILE *fp;

What is the use of fopen()?

fopen() opens an existing file or creates a file depending on the selected mode.

What is the use of fclose()?

fclose() closes an opened file and releases associated resources.

What is the difference between r, w, and a modes?

  • r → Read an existing file
  • w → Write to a file and potentially overwrite existing contents
  • a → Add data at the end of a file

What is random access in C?

Random access allows the file position indicator to be moved to a specific location using functions such as fseek().

Which functions are used for random file access?

The main functions are:

fseek()
ftell()
rewind()

File Handling in C is an essential concept for storing and managing data beyond the lifetime of a program. With functions such as fopen(), fclose(), fgetc(), fputc(), fprintf(), fscanf(), fseek(), ftell(), and rewind(), you can create practical programs that work with persistent data.

Once you understand file modes, file pointers, text and binary files, sequential access, and random access, you can build more practical C applications such as student management systems, billing programs, employee records, and inventory systems.



Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top