File Handling in C: Complete Guide to File Operations, File Pointers, Functions, and Real-World Applications

File Handling in C Programming – Complete Guide with Examples and Functions

Data is the backbone of every software application. Imagine a student management system that loses all student records whenever the program closes or a banking application that forgets every transaction after execution. Such software would be impractical and unreliable. This is where File Handling in C becomes essential. In C programming, data stored in variables exists only during program execution. Once the program terminates, the data stored in memory is lost. To overcome this limitation, C provides file handling mechanisms that allow programs to store data permanently on storage devices such as hard disks, SSDs, and pen drives. File handling enables developers to create, read, write, update, and manage data efficiently. It is widely used in banking systems, hospital management software, inventory applications, employee management systems, IoT devices, and embedded systems. In this comprehensive guide, you will learn everything about file handling in C programming, including file pointers, file operations, file handling functions, text files, binary files, and practical examples.

File Handling in C provides a mechanism for storing data permanently on storage devices, ensuring that information remains available even after program execution ends. C offers a wide range of file handling functions such as fopen(), fclose(), fscanf(), fprintf(), fseek(), and rewind() that enable efficient file creation, reading, writing, updating, and management. A strong understanding of file pointers, file operations, text files, binary files, and file positioning functions is essential for developing real-world applications such as banking systems, inventory software, hospital management systems, and embedded applications.

What is File Handling in C?

File Handling in C is the process of storing, retrieving, updating, and managing data in files using a C program. Unlike variables that store data temporarily in RAM, files store data permanently on secondary storage devices.

 

 

registor_now_P

 

 

Benefits of File Handling

  • Permanent data storage
  • Data retrieval across multiple program executions
  • Efficient management of large datasets
  • Data sharing between applications
  • Improved reliability and scalability

Without file handling, every program would lose its data after execution.

What is a File?

A file is a collection of related information stored permanently on a storage device.

Unlike variables, whose contents disappear when a program ends, file data remains available even after the system is turned off.

Examples of Files in Real Applications

  • Student records
  • Banking transactions
  • Employee information
  • Library databases
  • Hospital records
  • Configuration settings
  • Log files

Files help applications maintain data integrity and continuity.

Types of Files in C

Files in C are mainly classified into two categories.

1. Text Files

Text files store data as characters that can be read and understood by humans.

Examples:

  • .txt
  • .csv
  • .log
  • .c

Advantages

  • Easy to read
  • Easy to edit
  • Suitable for reports and logs

Disadvantages

  • Larger storage requirements
  • Slower processing

2. Binary Files

Binary files store data in the same format as it is represented in computer memory.

Examples:

  • .dat
  • .bin

Advantages

  • Faster processing
  • Reduced storage space
  • Better performance

Disadvantages

  • Not human-readable
  • Difficult to edit manually

Why Do We Need File Handling in C?

Consider the following situations:

  • A bank stores customer transaction history.
  • A hospital maintains patient records.
  • A school stores student marks.
  • An inventory system tracks product stock.

All these applications require data to remain available even after the program closes.

File handling provides:

  • Permanent storage
  • Secure record keeping
  • Large data management
  • Easy retrieval of information

This makes file handling one of the most important concepts in C programming.

What is a File Pointer in C?

Before accessing a file, a program must establish a connection with it. This connection is made using a file pointer.

A file pointer stores information about:

  • File location
  • Access mode
  • Current position
  • File status

Declaration of File Pointer


FILE *fp;

Here:

  • FILE is a predefined structure in
  • fp is a pointer to a file

Example


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

Once the file is opened, the returned address is stored in the file pointer.

 

 

Explore Courses - Learn More

 

 

File Operations in C

The most common file operations are:

  • Opening a file
  • Creating a file
  • Reading data
  • Writing data
  • Updating data
  • Managing file position
  • Closing a file

Opening a File in C

The fopen() function is used to open a file.

Syntax


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

Example


FILE *fp;

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

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

File Opening Modes in C

ModeDescription
rRead only
wWrite only
aAppend
r+Read and Write
w+Read and Write (Overwrite)
a+Read and Append

Understanding file opening modes in C is essential for performing correct file operations.

Creating a File in C

A file can be created using the “w” mode.

Example


FILE *fp;

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

If the file does not exist, it will be created automatically.

Reading Files in C

Reading allows programs to retrieve previously stored information.

C provides several functions for reading data.

fscanf() Function in C

Used for reading formatted data.

Syntax


fscanf(fp, "%d", &num);

Example


int age;

fscanf(fp, "%d", &age);

fgetc() Function in C

Reads one character at a time.

Syntax


char ch;

ch = fgetc(fp);

Example


char ch;

while((ch = fgetc(fp)) != EOF)
{
    printf("%c", ch);
}

fgets() Function in C

Reads an entire line from a file.

Syntax


fgets(str, sizeof(str), fp);

Example


char str[100];

fgets(str, 100, fp);

Writing Files in C

Writing allows data to be stored permanently.

fprintf() Function in C

Writes formatted output to a file.

Syntax


fprintf(fp, "%d", num);

Example


fprintf(fp, "Age = %d", age);

fputc() Function in C

Writes one character at a time.

Example


fputc('A', fp);

fputs() Function in C

Writes an entire string to a file.

Example


fputs("Welcome to IIES", fp);

File Positioning Functions in C

File positioning functions provide greater control over file access.

feof() Function

Checks whether the end of a file has been reached.

Example


while(!feof(fp))
{
    // Process file
}

fseek() Function

Moves the file pointer to a specified position.

Syntax


fseek(fp, offset, position);

Parameters

ParameterMeaning
offsetBytes to move
positionStarting point

Constants

ConstantMeaning
SEEK_SETBeginning of file
SEEK_CURCurrent position
SEEK_ENDEnd of file

Example


fseek(fp, 10, SEEK_SET);

ftell() Function

Returns the current file position.

Example


long pos;

pos = ftell(fp);

printf("%ld", pos);

rewind() Function

Moves the file pointer back to the beginning.

Example


rewind(fp);

This is useful when the same file needs to be processed multiple times.

Closing a File in C

Files should always be closed after use.

Syntax


fclose(fp);

Example


fclose(fp);

Closing files:

  • Releases system resources
  • Prevents memory leaks
  • Ensures data is saved correctly

Complete Program for File Handling in C


#include 

int main()
{
    FILE *fp;

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

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

    fprintf(fp, "Welcome to File Handling in C");

    fclose(fp);

    printf("Data written successfully");

    return 0;
}

Output


Data written successfully

Common Mistakes in File Handling

Many beginners make the following mistakes:

Not Checking fopen()


if(fp == NULL)

Always verify that the file opened successfully.

Forgetting fclose()

This can cause resource leaks.

Using Wrong Modes

Opening a file in “w” mode may erase existing content.

Reading Beyond EOF

Always check end-of-file conditions.

Ignoring File Pointer Position

Improper pointer handling can cause incorrect data retrieval.

Advantages of File Handling in C

  • Permanent storage
  • Efficient data management
  • Better scalability
  • Easy retrieval
  • Data portability
  • Real-world application support

Real-World Applications of File Handling

File handling is used extensively in software development.

Student Management Systems

Stores student details and marks.

Banking Applications

Maintains customer records and transaction history.

Hospital Management Systems

Stores patient information securely.

Employee Management Systems

Tracks employee records and payroll data.

Inventory Management Software

Maintains stock information.

Embedded Systems

Stores sensor logs and device configurations.

IoT Applications

Records real-time sensor data for analysis.

Library Management Systems

Maintains book and member information.

Conclusion

File Handling in C is a fundamental concept that enables programs to store and retrieve data permanently. By understanding file pointers, file opening modes, reading and writing functions, and file positioning operations, developers can build reliable applications capable of handling large amounts of information efficiently.

Whether you are developing a student management system, banking application, inventory software, embedded system, or IoT solution, mastering C file handling is essential. It not only improves programming skills but also provides the foundation for advanced topics such as binary file processing, random file access, and database integration.

 

 

Talk to Academic Advisor

Frequently Asked Questions

File handling in C is a mechanism used to store, retrieve, update, and manage data permanently using files on storage devices.

The <stdio.h> header file provides all standard file handling functions such as fopen(), fclose(), fscanf(), and fprintf().

Common functions include fopen(), fclose(), fscanf(), fprintf(), fgetc(), fputc(), fgets(), fputs(), fseek(), ftell(), rewind(), and feof().

A file pointer acts as a link between the program and the file, allowing read, write, and file positioning operations.

File handling is used in banking systems, student management systems, hospital databases, inventory software, embedded systems, and IoT applications.

Author

Embedded Systems trainer – IIES

Updated On: 23-06-26


10+ years of hands-on experience delivering practical training in Embedded Systems and it's design