File handling in C++ is managed through the <fstream> library, which provides three stream classes: std::ifstream (reading), std::ofstream (writing), and std::fstream (bidirectional read and write).
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 1. Write text to a file
{
std::ofstream outFile("veewom_notes.txt");
if (outFile.is_open()) {
outFile << "Mastering C++ File Streams\n";
outFile << "Built with RAII principles.\n";
}
} // Automatically flushed and closed on scope exit!
// 2. Read text line-by-line
{
std::ifstream inFile("veewom_notes.txt");
std::string line;
while (std::getline(inFile, line)) {
std::cout << "[READ]: " << line << "\n";
}
}
return 0;
}
#include <iostream>
#include <fstream>
struct PlayerData {
int id;
int score;
double health;
};
int main() {
PlayerData p1{101, 4500, 98.5};
// Write binary bytes directly to file
std::ofstream out("save.dat", std::ios::binary);
out.write(reinterpret_cast<const char*>(&p1), sizeof(PlayerData));
out.close();
// Read binary bytes back from file
PlayerData loadedPlayer{};
std::ifstream in("save.dat", std::ios::binary);
in.read(reinterpret_cast<char*>(&loadedPlayer), sizeof(PlayerData));
in.close();
std::cout << "Loaded Player ID: " << loadedPlayer.id << " | Score: " << loadedPlayer.score << "\n";
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Console stream manipulators and format flags.
Automatic deterministic file closing via destructors.
Throwing exceptions on file open errors.