FILE *f = fopen("notes.txt", "w");: modes"r"read,"w"write,"a"append.fprintf(f, ...)writes formatted text.fgets(line, size, f)reads a line.fclose(f)closes the file.
Always check that fopen did not return NULL.
Read and write files.
✍️ 2 exercises in this lessonFILE *f = fopen("notes.txt", "w");: modes "r" read, "w" write, "a" append.fprintf(f, ...) writes formatted text.fgets(line, size, f) reads a line.fclose(f) closes the file.Always check that fopen did not return NULL.
Mastering C Files helps you write clean and reliable C code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
#include <stdio.h>
int main() {
FILE *f = fopen("notes.txt", "w");
if (f == NULL) return 1;
fprintf(f, "Learn C\nBuild fast programs\n");
fclose(f);
char line[100];
f = fopen("notes.txt", "r");
while (fgets(line, sizeof line, f)) {
printf("> %s", line);
}
fclose(f);
return 0;
}
> Learn C > Build fast programs
Check what you learned in “C Files”.
Open a file for writing.
FILE *f = fopen("notes.txt", "");
What does fopen() return if it fails?
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services