File Streams
Overview
If your C++ program calculates the cure for cancer, but you close the terminal, the data is instantly vaporized from RAM. To make data persist permanently across reboots, you must write it to the Hard Drive.
C++ handles Files using Streams, specifically via the <fstream> header. Just like std::cout streams data to the terminal screen, an std::ofstream (Output File Stream) streams data directly into a text file on the SSD. Structurally, the syntax is identical, making file manipulation incredibly intuitive once you understand basic console output.
Syntax
#include <iostream>
#include <fstream> // Required for File Streams!
int main() {
// 1. OFSTREAM (Output File Stream)
// Opens the file (or creates it if it doesn't exist)
std::ofstream myFile("database.txt");
// 2. Validate the connection
if (myFile.is_open()) {
// 3. Write data using the exact same syntax as 'cout'
myFile << "Player: Arthur\n";
myFile << "Score: 9999\n";
// 4. Close the file (CRITICAL!)
myFile.close();
std::cout << "Data saved to Hard Drive!\n";
} else {
std::cout << "Fatal Error: Could not open file.\n";
}
return 0;
}Common Pitfalls
- Forgetting to
.close()the file. When you write data tomyFile, the OS often places it in a temporary RAM buffer to maximize speed. If your program crashes or you forget to close the file, the buffer is never 'flushed' to the physical Hard Drive, resulting in a completely blank or corrupted.txtfile.
Interview Questions
Yes! The std::ofstream and std::ifstream classes are beautifully engineered using RAII (Resource Acquisition Is Initialization). When the stream object goes out of scope and dies, its Destructor is mathematically guaranteed to flush the buffer and close the file. However, explicitly calling .close() is still considered best practice for readability and error-checking.
Real-World Example
Writing complex custom objects directly to a file by chaining the insertion operator.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string name = "Zelda";
int health = 100;
std::ofstream saveFile("save_slot_1.dat");
if (saveFile.is_open()) {
// Chaining data exactly like cout!
saveFile << name << "," << health << "\n";
saveFile.close();
}
return 0;
}Check Your Knowledge
Test your understanding of File Streams with these quick questions.