🔴 Advanced · Lesson 37
File Read & Write
File Read और Write
Character Read and Write
C Language
#include <stdio.h>
int main() {
FILE *fp = fopen("char.txt", "w");
fputc('A', fp);
fputc('B', fp);
fclose(fp);
fp = fopen("char.txt", "r");
int ch;
while((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}AB
String Read and Write
C Language
#include <stdio.h>
int main() {
FILE *fp = fopen("message.txt", "w");
fputs("Welcome to C File Handling\n", fp);
fputs("Learning is easy with practice\n", fp);
fclose(fp);
char line[100];
fp = fopen("message.txt", "r");
while(fgets(line, sizeof(line), fp) != NULL)
printf("%s", line);
fclose(fp);
return 0;
}Formatted Record I/O
C Language
#include <stdio.h>
int main() {
FILE *fp = fopen("marks.txt", "w");
fprintf(fp, "%d %s %d\n", 101, "Aman", 88);
fprintf(fp, "%d %s %d\n", 102, "Riya", 92);
fclose(fp);
int roll, marks;
char name[30];
fp = fopen("marks.txt", "r");
while(fscanf(fp, "%d %s %d", &roll, name, &marks) == 3) {
printf("%d %s %d\n", roll, name, marks);
}
fclose(fp);
return 0;
}Binary File using fwrite/fread
C Language
#include <stdio.h>
typedef struct {
int roll;
char name[30];
float marks;
} Student;
int main() {
Student s1 = {101, "Aman", 88.5}, s2;
FILE *fp = fopen("student.dat", "wb");
fwrite(&s1, sizeof(Student), 1, fp);
fclose(fp);
fp = fopen("student.dat", "rb");
fread(&s2, sizeof(Student), 1, fp);
fclose(fp);
printf("%d %s %.1f", s2.roll, s2.name, s2.marks);
return 0;
}Summary
- Use
fputc/fgetcfor character I/O - Use
fputs/fgetsfor string or line I/O - Use
fprintf/fscanffor formatted records - Use
fwrite/freadfor binary data - Always check file open status and close files
Character I/O
C Language
fputc('A', fp);
int ch = fgetc(fp);String I/O
C Language
fputs("Hello\n", fp);
fgets(line, sizeof(line), fp);Record I/O
C Language
fprintf(fp, "%d %s %d\n", roll, name, marks); fscanf(fp, "%d %s %d", &roll, name, &marks);
Binary File
C Language
fwrite(&s1, sizeof(Student), 1, fp); fread(&s2, sizeof(Student), 1, fp);
सारांश
- Character I/O के लिए fputc/fgetc
- Line/string के लिए fputs/fgets
- Formatted record के लिए fprintf/fscanf
- Binary data के लिए fwrite/fread
- File open check और fclose जरूरी है