File streams

The standard streams are not the only communication channels a program can use, a program can send or receive data directly on a file.

Even though you can use the command shell to redirect a program's standard streams to or from a file rather than the terminal, a program can otherwise choose to communicate to a file if it needs to.

This is an example of a program that creates a file and writes "hello world!" to it:

#include <fstream> using namespace std; int main() { ofstream f("example.txt"s); f << "hello world!"s << endl; return 0; }

The data type ofstream stands for output file stream, it represents a one-way portal for information to be written to a file. Once an output file stream has been created and associated with a file, you can use it the same way you would use the cout variable.

Notice how our ofstream is initialized. Unlike other data types (such as int, double, or even vector<int>), ofstream cannot be initialized with an assignment operator. You must initialize it with a list of values enclosed in parenthesis, it is similar to performing a function call.

If you want to initialize an ofstream variable, you must use the name of the file you want the ofstream to write data to. This file will be created if it doesn't exist, otherwise it is truncated.

We also have ifstream; when initialized with a file path, you can use it like you would with the cin object to read data from a file. This program displays all lines from example.txt into the terminal:

#include <iostream> #include <fstream> using namespace std; int main() { ifstream f("example.txt"s); string line; while (getline(f, line)) cout << line << endl; return 0; }

You may associate a different file with a file stream any time. This program uses one ofstream to write to multiple files one at a time:

#include <fstream> using namespace std; int main() { ofstream f;"data1.txt"s); f << "abc"s << endl; f << 123 << endl; f.close();"data2.txt"s); f << "def"s << endl; f << 456 << endl; f.close(); }

As you can see, f was first declared without an initial file association. The open member function associates a file with the file stream if none was already associated with it. The close member function disassociates the opened file with the current file stream.

You may check for any errors on the file stream by using it in a conditional statement. Consider the following code that may exist inside a main function:

ifstream f;"data.txt"s); if (not f) { cerr << "Failed to open file!" << endl; return 1; }

The variable f is treated as a boolean value within the If statement, it will be true if the stream is fully operational or false if: the stream failed to open, failed to read data, or failed to write data.

Notice the use of the new variable cerr, this is another standard stream like cout. cerr should be used when you want to output an error message from your program.