File Operations in C
In the previous lesson, you learned how to open and close files.
Now we will learn how to actually work with file data — writing data, reading data, and appending data.
These operations are the foundation of file-based programs.
Types of File Operations
There are three basic file operations:
- Writing data to a file
- Reading data from a file
- Appending data to a file
Writing Data to a File
Writing means storing data into a file. If the file already exists, its content will be erased.
We use "w" mode for writing.
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("info.txt", "w");
fprintf(fp, "C Programming File Operations");
fclose(fp);
return 0;
}
This program creates info.txt and writes text into it.
Reading Data from a File
Reading means fetching data from an existing file.
We use "r" mode for reading.
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("info.txt", "r");
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}
Each character is read one by one until the end of the file.
Appending Data to a File
Appending means adding data at the end of an existing file.
We use "a" mode for appending.
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("info.txt", "a");
fprintf(fp, "\nLearning at Dataplexa");
fclose(fp);
return 0;
}
The new text is added without deleting existing content.
Difference Between File Modes
- w → Write (overwrite existing content)
- r → Read (file must exist)
- a → Append (add data at end)
Real-World Example
Think of a diary:
- Write → start a new diary
- Read → read old pages
- Append → add today's entry
Mini Practice
- Create a file named
log.txt - Write a message into it
- Append another message
- Read and display full content
Quick Quiz
Q1. Which mode is used to write data?
w
Q2. Which function reads characters from a file?
fgetc()
Q3. Which mode keeps old content and adds new data?
a
Q4. What happens if you open a file in "w" mode?
Existing content is erased.
Q5. Is file reading possible if the file does not exist?
No.