Skip to content
Learn Netverks

Lesson

Step 32/36 89% through track

file-io-cpp

File I/O

Last reviewed May 28, 2026 Content v20260528
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++.

Teams still ship File I/O in C++ codebases—skipping it leaves gaps in debugging and code reviews.

You will apply File I/O in contexts like: Config loaders, log pipelines, and cross-platform desktop tools.

Write C++ in main.cpp with int main(), click Run on server—the dev runner compiles with c++/g++ -std=c++17 -Wall and runs the binary; read template errors in stderr (LEARNING_RUNNER_ENABLED=true).

Toward the end of the track—consolidate before capstone-style review lessons.

C++ streams (std::ifstream, std::ofstream) provide RAII file I/O—files close when streams destruct. Alternative: C fopen from C still works in C++.

Writing and reading

std::ofstream out("demo.txt");
out << "hello\n";
out.close();

std::ifstream in("demo.txt");
std::string line;
std::getline(in, line);

Always check is_open() or stream state after open operations.

Important interview questions and answers

  1. Q: RAII with streams?
    A: Destructor closes the file—avoid leaks even when exceptions throw.
  2. Q: Binary vs text mode?
    A: Use std::ios::binary on Windows for byte-exact I/O; POSIX often treats them similarly.

Self-check

  1. Which class reads from files?
  2. Why check is_open()?

Pitfall: Forgetting to check is_open() leads to silent failures—always verify stream state after open.

Interview prep

RAII with streams?

Stream destructors close files—cleanup happens even when exceptions throw.

Check open failure?

Use is_open() or test stream state—silent failures otherwise.

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

  • fstream vs C FILE?
  • RAII with files?

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