C Files

Read and write files.

✍️ 2 exercises in this lesson
  • 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.

Key Takeaways: C Files

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.

C Files Code Example

C
#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;
}
Output
> Learn C
> Build fast programs
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C Files Practice Exercises

Check what you learned in “C Files”.

/ 2 solved
Fill in the blank

Open a file for writing.

FILE *f = fopen("notes.txt", "");
✓ Correct! Not quite. Try again.
Multiple choice

What does fopen() return if it fails?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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