Lesson 25 of 50 · c
File I/O (`stdio.h`)
Duration: 10 mins
Files are accessed through FILE* streams.
FILE *fp = fopen("data.txt", "r");
if (!fp) { perror("open"); exit(EXIT_FAILURE); }
char line[128];
while (fgets(line, sizeof line, fp)) {
// process line
}
fclose(fp);
Modes:
r– read (file must exist).w– write (creates/overwrites).a– append.r+,w+,a+– read/write variants.
Always check the return of fread, fwrite, fprintf, and close the file with fclose.