File Handling Basics in C
Until now, all our programs worked only while they were running. Once the program stopped, all data was lost.
File handling allows C programs to store data permanently on the computer.
Using files, a program can:
- Save data for later use
- Read existing data
- Share data between programs
What Is a File?
A file is a collection of data stored on a disk with a name.
Examples:
- Student records
- Employee details
- Logs and reports
File Pointer (FILE *)
In C, files are accessed using a pointer of type FILE *.
FILE *fp;
This pointer connects your program to a file on disk.
Opening a File
The fopen() function is used to open a file.
fp = fopen("data.txt", "w");
If the file does not exist, it will be created.
File Opening Modes
- r – Read
- w – Write (overwrite)
- a – Append
Writing to a File
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("message.txt", "w");
fprintf(fp, "Welcome to Dataplexa!");
fclose(fp);
return 0;
}
This program creates a file and writes text into it.
Closing a File
Always close a file after using it.
fclose(fp);
Closing a file:
- Releases memory
- Saves data properly
Checking If File Opened Successfully
Always verify file opening.
if (fp == NULL) {
printf("File not opened");
}
Real-World Example
Think of file handling like writing in a notebook:
- Open notebook →
fopen() - Write notes →
fprintf() - Close notebook →
fclose()
Mini Practice
- Create a file named
student.txt - Write your name and roll number into it
Quick Quiz
Q1. Which pointer type is used for files?
FILE *
Q2. Which function opens a file?
fopen()
Q3. Which mode is used to write data?
w
Q4. Why should files be closed?
To save data and release resources.
Q5. What happens if a file pointer is NULL?
File opening failed.