Writing text files
A text file is a file that stores words and sentences in plain text. You must include the fstream.h header file before you can use files. You must then create a ofstream object which will let you open a file and output data to it. When creating the object you must put the name of the file you want to open in brackets. If the file does not exist it will be created and if it already exists it will be cleared.
You write to a file in a similar way as you write to the screen. All you have to do is replace cout with the name of the ofstream object.
f << "Hello";
Use the close method of the ofstream object to close the file when you are finished working with it. If you don't close a file then some data may not be written to it.
Appending to files
Files are cleared by default when you open them. If you want to add things to an existing file then you must open it for appending by using ios::app when opening the file.
Reading text files
You must declare an ifstream object instead of an ofstream when reading from files.
You need to declare a character array to store the data read when reading from a file. The character array can be any size as long as it is big enough to store what you are reading in.
Reading from a file is similar to using cin. Just replace cin with the name of the ifstream object.
f >> s;
Writing data files
A data file is a file that is usually used to store structures. First we will create a structure called teststruct.
Now let's declare a struct of the teststruct type and set its values.
ts.a = 5;
ts.b = 6;
You open a data file in the same way as a text file but you should give the file a .dat extension.
Writing to a data file is a bit more complicated. You must use the write method of the ofstream object. The first parameter of the write method is a pointer to the data structure to be written. The second parameter is the size of the object that you are writing.
Remember to close the file when you are finished writing to it.
Reading data files
To read from a data file we will first create an ifstream object and a structure of the teststructure type.
The read method of the ifstream object looks similar to the write method of the ofstream.
You should then test to see if the values were read properly by writing them to the screen.
cout << c.a << endl;
cout << c.b << endl;