Skip to content
Learn Netverks

Lesson

Step 23/36 64% through track

file-io

File I/O

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches File I/O: the syntax, patterns, and safety habits you need before advancing in C.

Buffered I/O and error checking appear in every CLI and embedded log pipeline.

You will apply File I/O in contexts like: Log parsers, config loaders, and portable CLI tools.

Write C in main.c with int main(), click Run on server—the dev runner compiles with cc/gcc -std=c11 and runs the binary; read stderr for compile and linker errors (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

The FILE * stream API in <stdio.h> reads and writes files. Always check return values and close files with fclose.

Open, read, close

FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { /* error */ }
fprintf(fp, "line\n");
fclose(fp);

Modes

  • "r" — read
  • "w" — write (truncate)
  • "a" — append

In the playground, file I/O may be limited—patterns still apply locally.

Important interview questions and answers

  1. Q: fopen failure?
    A: Returns NULL—check before use; errno may hold details.
  2. Q: fflush vs fclose?
    A: fflush pushes buffered data; fclose flushes and releases the stream.

Self-check

  1. Which function writes formatted text to a file?
  2. Why check fopen return value?

Pitfall: Forgetting fclose leaks file descriptors—in long-running servers this exhausts OS limits.

Interview prep

fopen failure?

Returns NULL—check before use; inspect errno for details on POSIX systems.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • fopen error check?
  • Binary vs text?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump