Writing to a Text File
Reading and Writing to a file is very easy. First we shall take a look at writing.
#include <iostream.h>
#include <fstream.h>
void main ( )
{
ofstream out("test.txt");
// Create a stream for output called out linked to test.txt
out<<"First "<<1<<endl;
out<<"Second "<<2<<endl;
out.close();
}
<< is known as the insertion operator. It is used for output along with the keyword cout (console out). Hence cout<<"Hi"; would actually write the word Hi on your screen (output). In the above program, instead of writing on the screen, we want to write to a particular file. Perhaps now you understand why we create an output stream for actually writing to a file. So we create a stream out for output and open the file test.txt.
out<<"First "<<1<<endl;
does the following things : it writes the word First and the number
1 to the stream out.
Remember that out has been linked to the file
test.txt. Hence First and 1 are written to the
file. Similarly Second and 2
are written on the next line of the file because of
the endl keyword. Finally we close the stream.
Go to the next section on Reading a Text File
or go back to Contents page 2.