đ§ĩ Complete Tutorial: File Functions in C
In C programming, file handling lets you save data permanently to a file, retrieve it later, and manage real-world data efficiently. You’ll use special functions like fopen()
, fclose()
, fprintf()
, and fscanf()
.
đš 1. FILE Pointer
Declare a file pointer using:
FILE *fp;
đš 2. fopen() – Open File
fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
Modes:
"r"
- Read"w"
- Write (overwrite)"a"
- Append"r+"
,"w+"
,"a+"
- Read + Write modes
đš 3. fprintf() – Write to File
fprintf(fp, "Name: %s, Age: %d\n", name, age);
đš 4. fscanf() – Read from File
fscanf(fp, "%s %d", name, &age);
đš 5. fclose() – Close File
fclose(fp);
Important to close files to release resources.
✅ Full Example: Student File Program
#include <stdio.h>
int main() {
FILE *fp;
char name[50];
int age;
fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("Cannot open file.\n");
return 1;
}
fprintf(fp, "Alice 20\nBob 25\nCharlie 22\n");
fclose(fp);
fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("Cannot open file.\n");
return 1;
}
printf("Reading from file:\n");
while (fscanf(fp, "%s %d", name, &age) != EOF) {
printf("Name: %s, Age: %d\n", name, age);
}
fclose(fp);
return 0;
}
đ Summary Table
Function | Purpose |
---|---|
fopen() | Open file in read/write mode |
fprintf() | Write to file with format |
fscanf() | Read from file with format |
fclose() | Close the file properly |
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ