Definition:
File handling allows us to store program output in a file and read data from a file — useful for permanent data storage.
Types of File Operations:
- fopen() – Opens a file
- fprintf() / fscanf() – Write/Read formatted data
- fgetc() / fputc() – Read/Write single characters
- fgets() / fputs() – Read/Write strings
- fclose() – Closes a file
Modes in fopen():
|
Mode |
Description |
|
“r” |
Open for reading |
|
“w” |
Open for writing (creates new or overwrites) |
|
“a” |
Append to file |
|
“r+” |
Read & write |
|
“w+” |
Write & read |
|
“a+” |
Append & read |
Example – Writing to a file:
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen(“data.txt”, “w”);
if (fptr == NULL) {
printf(“Error opening file!”);
return 1;
}
fprintf(fptr, “Hello File Handling!”);
fclose(fptr);
return 0;
}
Example – Reading from a file:
#include <stdio.h>
int main() {
FILE *fptr;
char ch;
fptr = fopen(“data.txt”, “r”);
while ((ch = fgetc(fptr)) != EOF) {
putchar(ch);
}
fclose(fptr);
return 0;
}