File I/O: Reading and Writing Persistent Data
6 min read
14. File I/O: Reading and Writing Persistent Data
Welcome back, developer! 🚀
Up until now, your C++ programs have suffered from a severe case of amnesia. You run the program, you input data, you calculate the meaning of life (42), and then... the moment you close the console, everything vanishes. Poof! 💨
This happens because variables live in RAM (Random Access Memory), which is volatile. To make your data survive a system reboot, a power outage, or just you closing the window, you need Persistence.
In this guide, we are going to learn how to talk to the hard drive. We will read from files, write to files, and learn the difference between human-readable text and efficient binary data.
Subtopic 1: File Streams: ifstream and ofstream
The Problem
std::cin and std::cout are great, but they are hardwired to the standard input (keyboard) and standard output (screen). You cannot easily redirect them to store a game save state or a configuration file.
The Solution
C++ provides the <fstream> library (File Stream). Just like water flows through a pipe, data flows through streams.
ifstream(Input File Stream): Used to read data from a file (Input from disk -> Program).ofstream(Output File Stream): Used to write data to a file (Program -> Output to disk).fstream: Can do both (but we usually stick to specific ones for safety).
🛠️ Industry Practice
Always include the header:
#include <fstream>Think of ofstream as cout that writes to a file, and ifstream as cin that reads from a file.
Subtopic 2: Opening, Closing, and Validating Files
Opening a File
To use a file, you must first create a stream object and associate it with a filename.
#include <iostream>
#include <fstream>
int main() {
// 1. Create the stream object and open the file in one step
std::ofstream myFile("gamelog.txt");
// Fun Fact: If "gamelog.txt" doesn't exist, ofstream creates it.
// If it DOES exist, by default, it deletes the content and starts fresh (Truncate).
return 0;
}The Problem: "Did it actually work?"
Hard drives are physical objects. Maybe the disk is full, maybe you don't have permission, or maybe the file is locked by an antivirus. If you try to write to a file that didn't open, your program will fail silently or crash.
The Solution: Validation
Always check is_open() before doing anything.
if (myFile.is_open()) {
// Safe to write
} else {
std::cerr << "Error: Could not open file!" << std::endl;
}Closing the File
In C++, we have a beautiful concept called RAII (Resource Acquisition Is Initialization).
- Manual Way:
myFile.close(); - The C++ Way: When the
myFileobject goes out of scope (end of the function or block), its destructor is called, and it automatically closes the file for you.
Industry Tip: You usually don't need to call
.close()explicitly unless you want to open a different file with the same stream object immediately after. Rely on the destructor to prevent resource leaks! 🛡️
File Modes
Sometimes you don't want to overwrite the whole file. You want to add to it.
| Mode Flag | Description |
|---|---|
std::ios::app |
Append. Writes are added to the end of the file. |
std::ios::binary |
Binary. Reads/writes raw bytes (no text formatting). |
std::ios::in |
Open for reading (default for ifstream). |
std::ios::out |
Open for writing (default for ofstream). |
Example: Appending to a log
std::ofstream logFile("server.log", std::ios::app); // Don't delete history, just add!Subtopic 3: Reading and Writing Text Data
Text I/O is designed to be human-readable. It handles characters, strings, and newlines automatically.
Writing Text
This is exactly like using cout.
#include <fstream>
#include <iostream>
int main() {
std::ofstream writer("todo_list.txt");
if(writer.is_open()) {
writer << "1. Buy Groceries" << "\n"; // Usage of insertion operator
writer << "2. Learn C++" << "\n";
writer << "3. Touch grass" << "\n";
}
return 0;
}Reading Text
The Problem with >>
The extraction operator >> stops reading at the first whitespace (space, tab, newline).
// If file contains: "John Smith"
std::string name;
reader >> name;
// name is now just "John". "Smith" is left in the buffer.The Solution: std::getline
To read persistent text data properly (like CSVs or config lines), use getline.
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream reader("todo_list.txt");
std::string line;
if (reader.is_open()) {
// while getline returns a valid stream (meaning it found a line), keep looping
while (std::getline(reader, line)) {
std::cout << "Read line: " << line << std::endl;
}
}
return 0;
}Imagination Time: Imagine
>>is a picky eater who stops eating as soon as he sees a space on the plate.getlineis a vacuum cleaner that sucks up everything until it hits the end of the line. 🧹
Subtopic 4: Handling Binary Files and Serialization Basics
The Problem
Text files are great for humans, but terrible for computers.
- Size: The number
123456789takes 9 bytes in text (one byte per digit), but only 4 bytes as a binary integer. - Precision: Converting floating-point numbers to text and back often loses precision.
- Speed: Parsing text is slow.
The Solution: Binary I/O
Binary files store the exact memory representation of your data on the disk. It looks like garbage to a human text editor, but it's fast for the CPU.
Serialization is the process of converting an object in memory into a format that can be stored or transmitted.
How to write Binary
We use the write function. It demands a char* pointer to the data and the size of the data.
Warning: This requires casting. 🧙♂️
#include <fstream>
#include <iostream>
struct PlayerData {
int id;
float health;
// WARNING: Do not use std::string or pointers here!
// Pointers point to RAM addresses which are invalid after reload.
// Use fixed-size char arrays for binary structs.
char name[20];
};
int main() {
PlayerData player = { 1, 99.5f, "Hero" };
std::ofstream outFile("savegame.bin", std::ios::binary);
if (outFile.is_open()) {
// reinterpret_cast tells C++: "Treat this PlayerData address as a simple sequence of bytes"
outFile.write(reinterpret_cast<char*>(&player), sizeof(PlayerData));
}
return 0;
}How to read Binary
We use the read function.
int main() {
PlayerData loadedPlayer;
std::ifstream inFile("savegame.bin", std::ios::binary);
if (inFile.is_open()) {
inFile.read(reinterpret_cast<char*>(&loadedPlayer), sizeof(PlayerData));
std::cout << "Loaded: " << loadedPlayer.name << " Health: " << loadedPlayer.health << std::endl;
}
return 0;
}⚠️ Industry Standard Warning
Binary files are sensitive to Endianness (byte order) and Padding (memory gaps). A binary file written on a Windows machine might not read correctly on a Linux server or a Mac if the architecture differs.
For complex, cross-platform data, industry professionals use serialization libraries like Protobuf, JSON, or MessagePack rather than raw write/read of structs. However, understanding raw binary I/O is essential for understanding how data is actually stored.
Summary
- Include:
<fstream>is your toolbox. - Streams:
ofstreamfor writing,ifstreamfor reading. - Validation: Always check
is_open(). - Text: Use
<<to write andstd::getline()to read. - Binary: Use
write()andread()withreinterpret_castfor high-performance data dumps, but be careful with pointers and cross-platform compatibility.
🔗 References & Further Reading
Challenge
Challenge: Binary Game State Serialization
You are tasked with creating a system to save and load a player's game state. To ensure efficiency and precision, the state must be stored in a binary file format.
Your goal is to implement two functions: saveState and loadState.
Requirements:
Define the Data Structure: A
structnamedPlayerStateis provided. You must work with this exact structure.Implement
saveState: This function takes a filename and a constant reference to aPlayerStateobject. It must:- Open the specified file in binary write mode.
- Perform a validation check to ensure the file was successfully opened. Return
falseon failure. - Write the entire, raw binary representation of the
PlayerStateobject to the file in a single operation. - Return
trueupon successful completion.
Implement
loadState: This function takes a filename and a non-constant reference to aPlayerStateobject which it will populate. It must:- Open the specified file in binary read mode.
- Perform a validation check to ensure the file was successfully opened. Return
falseon failure. - Read the binary data from the file directly into the provided
PlayerStateobject in a single operation. - Return
trueupon successful completion.
Constraints:
- You must include the
<fstream>header. - Use only the standard C++ library features covered in file I/O for this task. Do not use external libraries.
- Your solution must handle binary data correctly using the appropriate stream methods and casts.
Expected result
Your code should correctly implement the saveState and loadState functions according to the C++ standards for binary file I/O.
In saveState:
- An
std::ofstreamobject must be created with thefilenameand thestd::ios::binaryflag. - The code must check if the file was successfully opened using the
is_open()method or by evaluating the stream object in a boolean context (e.g.,if (!outFile)). - The function must call
ofstream::write(). - The first argument to
write()should be the address of thestateobject, cast toconst char*usingreinterpret_cast(e.g.,reinterpret_cast<const char*>(&state)). - The second argument to
write()must be the size of thePlayerStatestruct, determined usingsizeof(PlayerState).
In loadState:
- An
std::ifstreamobject must be created with thefilenameand thestd::ios::binaryflag. - Similar to saving, the code must validate that the file was successfully opened.
- The function must call
ifstream::read(). - The first argument to
read()should be the address of thestateobject, cast tochar*usingreinterpret_cast(e.g.,reinterpret_cast<char*>(&state)). - The second argument to
read()must be the size of thePlayerStatestruct, determined usingsizeof(PlayerState).
An explicit call to .close() is not necessary, as RAII will handle closing the file when the stream object goes out of scope, but including it is also acceptable.