Reading and Writing Text Files
fopen opens a file with a mode ("r", "w", "a"). Use fprintf, fgets and fclose, and always check for NULL.
Example
FILE *f = fopen("demo_c.txt", "w");
if (!f) return 1;
fprintf(f, "line one\nline two\n");
fclose(f);
f = fopen("demo_c.txt", "r");
char line[64]; int n = 0;
while (fgets(line, sizeof line, f)) { n++; printf("%d: %s", n, line); }
fclose(f);
remove("demo_c.txt");Result
1: line one 2: line two
Exercise
Open for appending.
fopen("a.txt", "")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.