So far, program data existed only while the program was running. Once the program ended, all variable data stored in memory was lost. File handling allows programs to store and retrieve data permanently using files stored on disk.
C provides file handling functions through the <stdio.h> library.
What is a File?
A file is a collection of data stored permanently on a storage device such as a hard disk, SSD, or flash memory.
Files allow programs to:
- Save data permanently
- Read previously stored information
- Process large amounts of data
- Exchange data between programs
File Pointer
In C, files are accessed using a special pointer called a file pointer.
Syntax
FILE *fp;
The FILE type is defined inside <stdio.h>.
Opening a File
The fopen() function is used to open a file.
Syntax
fp = fopen("filename", "mode");
Common File Modes
| Mode | Purpose |
|---|---|
| "r" | Open file for reading |
| "w" | Open file for writing |
| "a" | Open file for appending |
| "r+" | Read and write |
| "w+" | Read and write (overwrites file) |
Example Program & Output [ Click to View ]
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("data.txt", "w"); // opens in write mode
if(fp == NULL)
{
printf("File opening failed");
return 1;
}
fprintf(fp, "Hello File"); // writes data
fclose(fp); // closes file
printf("Data written successfully");
return 0;
}
Output
Note: "w" mode autocreates missing files.
Reading from a File
The fscanf() function reads formatted data from a file.
Example
fscanf(fp, "%s", data);
Closing a File
The fclose() function closes an opened file.
Syntax
fclose(fp);
Closing files properly prevents resource leaks and ensures data is saved correctly.
File Handling Flow
Important Points
- → Files store data permanently outside normal program memory
- →
FILE *pointers are used to access and manage files - → Always check if
fopen()returnsNULLbefore performing file operations - →
fclose()should be used to properly save data and release file resources
Embedded Focus
File handling is used in embedded Linux systems, logging systems, configuration storage, and SD card interfaces.
FILE *log = fopen("sensor_log.txt", "a");
Embedded applications often use files for storing logs, configuration parameters, sensor readings, and communication data.