đ§ĩ Reading and Writing Text & Binary Files in C
đļ Text vs Binary Files
Type | Description |
Text File | Stores data in human-readable form |
Binary File | Stores data in machine-readable form |
đš Writing to a Text File
#include <stdio.h>
int main() {
FILE *fp = fopen("textfile.txt", "w");
fprintf(fp, "Hello World!\n");
fprintf(fp, "This is a text file.\n");
fclose(fp);
return 0;
}
đš Reading from a Text File
#include <stdio.h>
int main() {
FILE *fp = fopen("textfile.txt", "r");
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp)) {
printf("%s", buffer);
}
fclose(fp);
return 0;
}
đš Writing to a Binary File
#include <stdio.h>
struct Student {
int id;
float marks;
};
int main() {
struct Student s1 = {101, 88.5};
FILE *fp = fopen("student.dat", "wb");
fwrite(&s1, sizeof(struct Student), 1, fp);
fclose(fp);
return 0;
}
đš Reading from a Binary File
#include <stdio.h>
struct Student {
int id;
float marks;
};
int main() {
struct Student s2;
FILE *fp = fopen("student.dat", "rb");
fread(&s2, sizeof(struct Student), 1, fp);
printf("ID: %d\nMarks: %.2f\n", s2.id, s2.marks);
fclose(fp);
return 0;
}
đ Summary
- Text File: Readable, editable but slow
- Binary File: Compact, fast, ideal for structures
C file handling tutorial, read and write text files in C, binary file handling in C, fwrite fread fopen fclose, structure with file, C programming file example
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ