File handling in C refers to the process of storing data permanently in files and retrieving it when required. Unlike variables, which store data temporarily in memory, files allow data to be stored permanently on secondary storage devices.
File handling is essential for programs that need to save data, process large inputs, or share information between multiple executions of a program.

In C programming, files are broadly classified into two types:
Text files store data in human-readable form, whereas binary files store data in machine-readable (binary) format.
A file pointer is a pointer of type FILE used to access a file.
It acts as a connection between the program and the file.
FILE *fp;
The file pointer keeps track of the current position in the file during read or write operations.
Files are opened using the fopen() function with a specific mode.
The mode determines the type of operation to be performed on the file.
| Mode | Description |
|---|---|
| r | Opens a file for reading |
| w | Opens a file for writing (creates a new file) |
| a | Opens a file for appending |
| r+ | Opens a file for reading and writing |
| w+ | Opens a file for reading and writing |
| a+ | Opens a file for reading and appending |
C provides several functions to read data from files. The commonly used file reading functions are:
fgetc() – Reads a single characterfgets() – Reads a string from a filefscanf() – Reads formatted data
char ch = fgetc(fp);
fgets(str, sizeof(str), fp);
fscanf(fp, "%d", &num);
File writing functions are used to write data into files.
fputc() – Writes a single characterfputs() – Writes a stringfprintf() – Writes formatted output
fputc('A', fp);
fputs("Hello", fp);
fprintf(fp, "%d", num);
After completing file operations, the file must be closed using the fclose() function.
Closing a file ensures that all data is saved properly and releases system resources.
fclose(fp);
Failure to close a file may lead to data loss or memory leaks.
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("data.txt", "w");
if (fp == NULL)
{
printf("File cannot be opened");
return 1;
}
fprintf(fp, "Welcome to C File Handling");
fclose(fp);
return 0;
}
This program creates a file and writes text into it using file handling functions.