First publication date: 2020/04/27
Characters streams
We will deal with basic handling of data streams with a focus on text files.
You will need to include the fstream
header and do NOT forget to use the std::
prefix (or the proper use
statement)
You are already using predefined in your programs :
std::cout
: the standard output streamstd::cin
: the standard input streamstd::cerr
: the standard error output stream
These streams can be redirected to files if needed but we can also use these streams directly.
Writing in a stream
To see how you can write in a file, let's analyse the following piece of code :
std::string name = "my_file.txt";
std::ofstream file(name.c_str());
if (!file.fail()) {
file << amount << std::endl;
for (int i = 0; i < amount; ++i)
file << i+1 << std::endl;
file.close();
- Line 1: declaration of a variable of
string
type referring to the name of the file - Line 2: declaration of a writing stream variable. The constructor takes the name of the file as a parameter.
The same result can be achieved with
open()
- Line 4: if the file is not null, the file is opened otherwise it means a problem occured.
- Lines 5 & 7: we write to the file the same way we use
std::cout
- Line 9: the stream is closed. It is optionnal in this case because the stream destructor closes it anyway.
If you do not know what nom.c_str()
means, go back to the notice about strings.
Reading from a stream
std::ifstream file; // other way to open a file
int i = 0, max;
file.open(name.c_str());
// fail() not tested :-(
file >> max;
while(!file.eof() && i<max) {
double reading;
file >> reading;
++i;
std::cout << reading << " ";
}
file.close();
- Line 1: declaration of a input stream
- Line 4: associates the stream with a file
- Line 6: reading from the stream/file
- Line 8: test of the
eof()
flag. This flag is only updated after reading.
Stream types
We just saw a first type of streams (characters streams for text files). The page on strings gives another type of stream, not associated to a file but to a string. Handy, isn't it ?
We can use binary streams as well but there is no serialization concept in C++, unfortunately.