Hi, please, what contains the fstream variable? A can find many tutorials on fstream, but no ona actually says what is the fstream file; declaration in the beginning. Thanks.
An fstream object is used to open a file for input (i.e. reading the contents of the file) and output (i.e. writing to the file).
There are also ifstream and ofstream objects, which separate input and output into two different objects. This is useful if, for example, you wanted to read an unformatted file and write the formatted output to a different file.
std::fstream is a class that incapsulates the read/write access to a file. It inherits from iostream, so it sports all the usual methods provided by all the C++ streams to read and write to the file. For more information see its documentation and the chapter about IO of your C++ manual.
The fstream class is an object that handles file input and output. It is mostly equivalent to both an ifstream and ostream object in one, in that you can use it for both input and output. This tiny demonstration will create a file and write data to it.
#include <fstream>
using namespace std;
int main()
{
fstream myFile;
myFile.open("data.txt");
myFile << "This will appear in the file.";
myFile.close();
}
What is cool about fstream objects is that you can use them to read and write binary memory images to files (to protect your file's data from editing) and set various flags to control the way in which the fstream processes input and output. For example:
This fstream is an output stream that clears fout.txt's data and writes in binary.
fstream foutOne("fout.txt", ios::binary | ios::out | ios::trunc)
This fstream is an output stream that does not clear fout.txt's data, but appends to the end of it instead, and writes in binary.
fstream foutTwo("fout.txt", ios::binary | ios::out | ios::app)
If I remember right, foutTwo will crash if fout.txt does not exist, while foutOne will not. You can (and should ALWAYS) check if the fstream loaded correctly immediately after opening a file like so:
if(!foutTwo)
{ cout << "File open error!\n"; exit(EXIT_FAILURE); }