File Input/Output
Master reading from and writing to files using C++ file streams
Learn how to persist data beyond program execution by reading from and writing to files using C++ file streams.
A Simple Example
#include <iostream>
#include <fstream>
#include <string>
void writeFile() {
std::ofstream outFile{"data.txt"};
if (!outFile) {
std::cerr << "Failed to open file for writing\n";
return;
}
outFile << "Hello, File!\n";
outFile << "Numbers: " << 42 << " " << 3.14 << "\n";
outFile << "Multiple lines\n";
// File automatically closed when outFile goes out of scope
}
void readFile() {
std::ifstream inFile{"data.txt"};
if (!inFile) {
std::cerr << "Failed to open file for reading\n";
return;
}
std::string line;
while (std::getline(inFile, line)) {
std::cout << "Read: " << line << "\n";
}
// File automatically closed when inFile goes out of scope
}
int main() {
writeFile();
readFile();
return 0;
}
Breaking It Down
std::ofstream - Output File Stream
- What it does: Opens a file for writing output
-
Syntax:
std::ofstream outFile{"filename.txt"}; - Default behavior: Creates the file if it doesn't exist, overwrites if it does
-
Remember: Use
<<operator just like with std::cout
std::ifstream - Input File Stream
- What it does: Opens a file for reading input
-
Syntax:
std::ifstream inFile{"filename.txt"}; -
Reading: Use
>>for formatted input orstd::getline()for whole lines -
Remember: Check if file opened successfully with
if (!inFile)
File Stream Checking
- Why check: Files might not exist, permissions might be denied, disk might be full
-
How to check:
if (!file)orif (file.fail()) - Best practice: Always check immediately after opening a file
- Remember: Failed stream operations are silently ignored unless checked
RAII and Automatic Cleanup
- What it means: Resource Acquisition Is Initialization
- How it works: File automatically closes when stream object goes out of scope
- Why it matters: No manual close() needed, prevents resource leaks
- Remember: The destructor handles cleanup automatically
Why This Matters
- Most real programs persist data: saving game progress, processing log files, reading configuration, exporting reports.
- File I/O is fundamental to making programs useful beyond a single execution.
- C++'s stream-based approach makes file operations consistent with console I/O you already know.
Critical Insight
File streams are just specialized versions of the iostream you already know. That's why << and >> work the same way with files as they do with std::cin and std::cout. Once you master one stream type, you've mastered them all.
Plus, because streams use RAII (Resource Acquisition Is Initialization), you never have to remember to close files - they close themselves when they go out of scope. This prevents resource leaks and makes your code safer.
Best Practices
Always check if file opened: Use if (!file) immediately after opening to catch file not found or permission errors.
Use RAII for automatic cleanup: Let the stream's destructor close the file automatically instead of calling close() manually.
Use getline() for text files: When reading line-by-line, std::getline(file, line) is cleaner than the >> operator.
Prefer uniform initialization: Use std::ofstream file{"name.txt"} instead of std::ofstream file("name.txt").
Common Mistakes
Forgetting to check if file opened: Always check if (!file) after opening - the file might not exist or you might lack permissions.
Not using append mode: Opening with just std::ofstream truncates the file. Use std::ios::app to preserve existing content.
Mixing formatted and unformatted I/O: Don't mix >> with getline() - >> leaves the newline in the buffer, causing getline() to read an empty line.
Forgetting to include <fstream>: File streams require #include <fstream>, not just #include <iostream>.
Debug Challenge
This code tries to write to a file but has a bug. Click the highlighted line to fix it:
Quick Quiz
- What happens when an ofstream goes out of scope?
- Which mode should you use to add to an existing file without erasing it?
- What does getline() return when it reaches end of file?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once