🔴 Advanced · Lesson 36
File Handling in C
File Handling
File Handling
File handling allows a C program to store data permanently in files and read it later. C uses FILE pointer and functions from stdio.h.
| Function | Use |
|---|---|
fopen() | Open file |
fclose() | Close file |
fprintf() | Write formatted data |
fscanf() | Read formatted data |
fgets() | Read a line |
fputs() | Write a string |
File Modes
| Mode | Meaning |
|---|---|
r | Open existing file for reading |
w | Create/overwrite file for writing |
a | Append data at end |
r+ | Read and write existing file |
w+ | Read and write, overwrite/create |
a+ | Read and append |
Write File
C Language
#include <stdio.h>
int main() {
FILE *fp = fopen("students.txt", "w");
if(fp == NULL) {
printf("File cannot be opened");
return 1;
}
fprintf(fp, "Roll Name Marks\n");
fprintf(fp, "101 Aman 89\n");
fprintf(fp, "102 Riya 94\n");
fclose(fp);
printf("Data written successfully");
return 0;
}Read File
C Language
#include <stdio.h>
int main() {
FILE *fp = fopen("students.txt", "r");
char line[100];
if(fp == NULL) {
printf("File not found");
return 1;
}
while(fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);
return 0;
}Summary
- Use
FILE *for file operations - Always check if
fopen()returnsNULL - Close every opened file using
fclose() - Use correct mode: read, write or append
- Use text functions for simple text files
File Handling
File handling से C program data को permanently files में store और later read कर सकता है। इसके लिए stdio.h के functions use होते हैं।
File Modes
| Mode | Meaning |
|---|---|
r | Read existing file |
w | Write/overwrite |
a | Append |
r+ | Read + write |
w+ | Read + write, overwrite |
File Write
C Language
FILE *fp = fopen("data.txt", "w");
if(fp == NULL) {
printf("File error");
return 1;
}
fprintf(fp, "Hello File");
fclose(fp);File Read
C Language
FILE *fp = fopen("data.txt", "r");
char line[100];
while(fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);सारांश
- File handling permanent data storage देती है
FILE *pointer use होता हैfopen()के बाद NULL check करें- काम पूरा होने पर
fclose()करें - Mode सही choose करें