C Workshop · File Handling
Foundation C

File Handling

A FILE* is a handle from fopen. You write with fprintf, then fclose so the data actually lands on disk.

What it is

A file on disk is a stream of bytes with a name. fopen gives you a handle (FILE*), you read or write through that handle, then fclose so the data actually lands and the handle is released.

Approach

  1. fopen with a mode (w, r, or a).
  2. If the pointer is NULL, stop.
  3. Read or write.
  4. fclose.

Where this is used in the real world

Diagram

1

fopen

notes.txt

2

fprintf

Hello

3

fclose

save

4

disk

Hello

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    FILE *f = fopen("notes.txt", "w");
4    if (!f) return 1;
5    fprintf(f, "Hello\n");
6    fclose(f);
7    printf("OK\n");
8    return 0;
9}
What this line does
Press Run algorithm. The highlight will move through the C code.
file is closed
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. fopen(..., "w") will:

Write mode.

2. If fopen returns NULL:

Check.

3. fprintf is like printf but:

To a file.

4. fclose is needed because:

Close.

5. "r" vs "w":

Mode.