C++ ifstream & ofstream
In this page:
#include <fstream>
std::ofstream out("filename.txt");
out << value;
out.close();
std::ifstream in("filename.txt");
in >> variable;
in.close();
Writing with ofstream
std::ofstream is specialized for writing to files, and reuses the insertion operator (<<) you already know from std::cout -- once a file is open, file << "text" writes to it exactly the same way cout << "text" writes to the console.
Example: Writing with ofstream
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>
// Program execution starts in main()
int main() {
std::ofstream file("data.txt");
file << "Hello file";
file.close();
// Print to the console with cout
std::cout << "Written" << std::endl;
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading with ifstream
std::ifstream is specialized for reading from files, using the extraction operator (>>) just like std::cin. It reads whitespace-delimited tokens one at a time -- numbers, words -- converting them to the target variable's type automatically.
Example: Reading with ifstream
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>
// Program execution starts in main()
int main() {
std::ofstream out("data.txt");
out << "42";
out.close();
std::ifstream in("data.txt");
int value;
in >> value;
// Print to the console with cout
std::cout << value << std::endl;
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading Line by Line
Because >> stops at whitespace, it can't read a line containing spaces in one call -- reading "Hello World" would stop at "Hello". std::getline(stream, str) reads an entire line, including internal spaces, up to the next newline, which is what you want for sentence- or record-based file formats.
Example: Reading Line by Line
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>
#include <string>
// Program execution starts in main()
int main() {
std::ofstream out("data.txt");
out << "Hello World";
out.close();
std::ifstream in("data.txt");
std::string line;
std::getline(in, line);
// Print to the console with cout
std::cout << line << std::endl;
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Appending with ofstream
Opening a file with plain ofstream truncates it, discarding any existing content before writing begins.
Passing the ios::app flag instead positions every write at the end of the existing file, letting you add new data (like log entries) without destroying what was already saved.
Example: Appending with ofstream
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>
// Program execution starts in main()
int main() {
std::ofstream file("data.txt", std::ios::app);
file << "Appended text";
file.close();
// Print to the console with cout
std::cout << "Appended without truncating" << std::endl;
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Safe File Writing Practices
Beyond just checking is_open(), inspect the stream's state after each read or write -- a failed write (for example, from a full disk) sets the fail bit even though the stream opened successfully, and code that doesn't check this can silently lose data.
Example: Safe File Writing Practices
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>
// Program execution starts in main()
int main() {
std::ofstream file("data.txt");
file << "Some data";
// Check whether file.fail()
if (file.fail()) {
// Print to the console with cout
std::cout << "Write failed" << std::endl;
} else {
// Print to the console with cout
std::cout << "Write succeeded" << std::endl;
}
file.close();
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
- Not checking that
ofstreamorifstreamopened successfully before using it, so a missing file goes unnoticed. - Opening an existing file with
ofstreamin the default mode, which erases its old content; useios::appto append. - Reading lines with
while (!file.eof()), which often processes the last line twice; loop ongetlineinstead.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: