A file stream reads from and writes to a file. It is available from the fstream header. There are three different kinds of file streams:
std::ofstream#include <fstream>writes to a file.std::ifstream#include <fstream>reads from a file.std::fstream#include <fstream>does both.
std::ofstream#include <fstream> writes to a file with <<, and close() closes the stream:
#include <fstream>
std::ofstream#include <fstream> out("scores.txt");
out << "Alice 30\n";
out << "Bob 25\n";
out.close();Note
The file is also closed automatically when the object goes out of scope.
std::ifstream#include <fstream> parses values from an existing file with >>. Converting the stream to bool checks whether the file opened:
std::ifstream#include <fstream> in("scores.txt");
if (!in) {
std::cerr#include <iostream> << "Could not open scores.txt.\n";
}
std::string#include <string> word;
while (in >> word) {
std::cout#include <iostream> << word << "\n";
}Flags
std::ofstream#include <fstream> creates the file when it opens it, or empties it if it already exists. To keep the existing file content, pass std::ios::app to append to the file:
std::ofstream#include <fstream> log("log.txt", std::ios::app);
log << "Started.\n";The flags that can be passed are:
std::ios::in: open for reading.std::ios::out: open for writing.std::ios::app: append every write to the end.std::ios::ate: start at the end, but allow seeking.std::ios::trunc: empty the file on open.std::ios::binary: no newline translation.
Multiple flags can be combined with |:
std::fstream#include <fstream> file("data.bin", std::ios::in | std::ios::out | std::ios::binary);File streams can be opened with a std::string#include <string>. Before C++11, the filename had to be a const char*, so c_str() was needed:
std::string#include <string> filename = "scores.txt";
std::ifstream#include <fstream> a(filename); // C++11.
std::ifstream#include <fstream> b(filename.c_str()); // C++98.References
- cppreference: std::basic_fstream
- cppreference: std::basic_ifstream
- cppreference: std::basic_ofstream
Dan