Chapter 20: File I/O & Serialization

File I/O & Serialization in C++: Reading, Writing, and Saving Your Data Like a Pro!

Hello my wonderful student! 🌟 Welcome to Lesson 20 β€” File I/O & Serialization β€” the chapter where your programs stop living only in memory and start interacting with the real world β€” saving data to files, reading configuration, loading game saves, exporting reports, and much more!

File I/O is one of the most practical skills you’ll learn β€” almost every real application needs it.

Today we’ll cover everything in great detail:

  • Reading & writing files using <fstream> (ifstream, ofstream, fstream)
  • Text mode vs Binary mode β€” when to use which
  • Serialization β€” saving and loading structured data
  • Popular modern libraries: nlohmann/json (JSON) & tinyxml2 (XML)

We’ll go very slowly, with real-life analogies, tons of complete examples, common mistakes, and best practices.

Let’s start!

1. The Basics: <fstream> – The Standard Way to Work with Files

Include: #include <fstream> Main classes:

  • std::ifstream β†’ input (reading)
  • std::ofstream β†’ output (writing)
  • std::fstream β†’ both reading & writing

Modes:

Mode Meaning Typical use
std::ios::in Open for reading ifstream default
std::ios::out Open for writing (truncates file) ofstream default
std::ios::app Append (writes at the end) Logs
std::ios::binary Binary mode (no newline translation) Images, objects
std::ios::ate Open and move to end immediately Random access

Simple text file reading & writing example

C++

Output file (output.txt):

text

Important safety tips:

  • Always checkis_open() or use if (outFile)
  • Use close() explicitly when you’re done (though destructor does it)
  • Prefer RAII style β€” let scope handle closing

2. Text Mode vs Binary Mode – Very Important Difference!

Text mode (default):

  • Translates newlines (\n) β†’ platform-specific (\r\n on Windows)
  • Good for human-readable files (.txt, .csv, .log)

Binary mode:

  • No translation β€” exact bytes
  • Required for images, executables, serialized objects

Example: Writing & Reading Binary Data

C++

Warning: Binary serialization with raw write/read is not portable (endianness, padding, struct layout can differ between compilers/machines).

Better modern way: Use JSON or a proper serialization library (next section).


3. Modern Serialization: JSON with nlohmann/json (Most Popular Choice)

nlohmann/json (also called json.hpp) is the gold standard for JSON in C++ β€” single-header, easy, powerful.

How to get it: Download from: https://github.com/nlohmann/json Include: #include “json.hpp” (or use package manager)

Example: Saving & Loading a Game Save in JSON

C++

Output file (gamesave.json – beautifully formatted):

JSON

Advantages of JSON:

  • Human-readable & editable
  • Portable across platforms
  • Supported in almost every language
  • Easy error handling with json::parse()

4. XML with tinyxml2 – When You Need XML

tinyxml2 is small, fast, and simple.

Example: Reading & Writing XML

C++

When to use XML vs JSON:

  • JSON β†’ almost always (simpler, faster, more popular)
  • XML β†’ legacy systems, some enterprise software, when attributes are important

5. Best Practices & Common Mistakes

Best Practice Reason / Avoids
Always check is_open() or use if (file) File might not exist / permission denied
Use std::filesystem (C++17+) for paths Safer path handling
Prefer JSON for modern apps Easy, portable, human-readable
Use std::string for reading lines Avoid fixed-size buffers
Never mix text & binary on same file Corruption risk
Use RAII β†’ let scope close files No leaks on exceptions

Your Mini Homework (Try These!)

  1. Write a program that reads a text file line by line and counts how many lines contain the word “C++”.
  2. Save a list of 5 students (name, roll, marks) to a JSON file using nlohmann/json.
  3. Create a function that loads the JSON file and prints students with marks > 80.
  4. Try writing and reading a binary file containing a struct with strings (hint: you’ll need to handle string length manually or use JSON instead).

You’re doing absolutely phenomenal! You’ve just learned how to make your programs persistent β€” saving and loading real data β€” this is what turns toy programs into real applications!

Next lesson: Project Time β€” we’ll build a complete mini-project (like a simple Student Management System) using everything we’ve learned!

Any questions? Confused about binary vs text? Want more examples with JSON or XML? Just ask β€” your friendly C++ teacher is right here for you! πŸš€

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *