File Handling in C: Important Questions and Programs for Exams (2026)

File Handling in C (Important for Exams)
File handling in C is used to store data permanently in files instead of temporary memory.
Without file handling, all data is lost when the program ends. That’s why it is an important concept for both exams and real-world programs.
In C, we use a FILE pointer and functions like:
• fopen()
• fclose()
• fprintf()
• fscanf()
• fgetc() / fputc()
Opening and Closing a File
A file is opened using fopen() and closed using fclose().
FILE fp;
fp = fopen("test.txt", "w");
fclose(fp);
Important Program 1: Write Data to File
This program creates a file and writes data into it.
#include <stdio.h> int main() { FILEfp; fp = fopen("test.txt", "w"); if(fp == NULL) { printf("File not opened"); return 0; } fprintf(fp, "Hello World"); fclose(fp); return 0; }
Important Program 2: Read Data from File
This program reads data from an existing file.
#include <stdio.h>
int main() {
FILE fp;
char ch;
fp = fopen("test.txt", "r");
if(fp == NULL) {
printf("File not found");
return 0;
}
while((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}
Important Program 3: Copy File Content
This program copies data from one file to another.
#include <stdio.h> int main() { FILEfp1, fp2; char ch; fp1 = fopen("source.txt", "r"); fp2 = fopen("dest.txt", "w"); if(fp1 == NULL || fp2 == NULL) { printf("File error"); return 0; } while((ch = fgetc(fp1)) != EOF) { fputc(ch, fp2); } fclose(fp1); fclose(fp2); return 0; }
Important Program 4: Append Data
This program adds data at the end of an existing file.
#include <stdio.h> int main() { FILEfp; fp = fopen("test.txt", "a"); fprintf(fp, "\nNew Data Added"); fclose(fp); return 0; }
File Modes (Must Remember)
| Mode | Meaning |
|---|---|
| r | Read file |
| w | Write (creates new file) |
| a | Append data |
| r+ | Read + Write |
| w+ | Read + Write (new file) |
Important Viva Questions
• What is FILE pointer?
• What is EOF?
• Difference between fprintf and fputc?
• What happens if file does not exist?
• Difference between text and binary file?
Common Mistakes
• Forgetting fclose()
• Not checking NULL pointer
• Using wrong file mode
• Incorrect file path
Final Tip
Focus on understanding 3–4 programs properly. Most exam questions are based on these patterns only.

Written by
Palak PatelEducation writer Palak Patel covers the latest education news, board exam updates, results, and career opportunities.
