Basics
We have been dealing with input and output streams this whole time which are cin and cout
respectively. The input/output stream is used with the <iostream> library.
In C++, as well as any programming language, you can read and write to a text file (.txt extension).
This is done in a similar way to the input/output stream in terms of the library to include with the
program. C++ provides 3 of them:
One important thing to note is that the input is treated the same as cin while the
output is treated the same as cout.
Output
In order to do both input or output, you must open a file before anything else occurs. The same
as a variable, the stream you are using is a type. So here is a short program that shows some
simple output to a text file.
Example 1:
Simple output
Download source code here (Right click - Save Tagret As...)
The above program will simply open a text file for output (ofstream), check to see if the
file is correctly opened, write a line to the file and close the stream.
Here is a bit more detail about the above programs functions.
open()
The open() function will simply open a file for either input or output. The above program
did it for output. The parameter of the function will be the file name. If the file does not
exist in the directory, C++ will create it for you.
close()
A simple function designed to close the file and it's stream. It will require no parameters.
is_open()
The is_open() function is a boolean function that will check whether or not a file is open.
If the function returns true, the file is open without any problems. If it returns false,
the file is not good and therefore cannot be used.
Recalling from the previous tutorial about the getline() function, input from text files
are used in that fashion. Input of files also require the <string> library for the getline()
function.
Here is an example of file input. The file must be created first in order for this to work.
Example 2:
Simple input
Download source code here (Right click - Save Tagret As...)
This program will attempt to read a file for input, display the line you read and
then close the file.
Here is some information about the new function eof() which stands for "end of file".
eof()
The eof() function is a boolean function that will check whether or not the file has reached
the end. It returns true when the file is at the end and false otherwise.