C Workshop · Read a Line
Lesson C

Read a Line

fopen with "r", then fscanf or fgets into a buffer, then print what you read.

What it is

Read mode opens an existing file and copies bytes into your variables. Here the file already holds Hello. fscanf pulls that word into a buffer, then printf shows it on the screen.

Approach

  1. fopen(..., "r").
  2. fscanf into a buffer.
  3. printf the buffer.
  4. fclose.

Where this is used in the real world

Diagram

1

r

open

2

fscanf

Hello

3

printf

Hello

4

fclose

done

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    char buf[64];
4    FILE *f = fopen("notes.txt", "r");
5    if (!f) return 1;
6    fscanf(f, "%63s", buf);
7    printf("%s\n", buf);
8    fclose(f);
9    return 0;
10}
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. This run prints:

fscanf then printf.

2. "r" fails when:

NULL.

3. fgets vs fscanf %s:

Line vs word.

4. After fscanf, you should still:

Close.

5. Binary read uses:

Another kind.