File Input and Output
If you want to prepare input data ahead of time, you might store the data in a file and direct the program to read its' input from a file. If you want to save output data in a file to use later, you may direct the program to write to a file. To read and/or write to a file, do the following:
- Request the preprocessor to include file
fstream
as well asiostream
.fstream
contains the declarations for defining input and output streams with files other thancin
andcout
. - Declare an input stream to be of type
ifstream
or an output stream to be of typeofstream
. - Prepare the stream for use by using the function named
.open()
provided in filefstream
. The parameter for the function.open()
is the name under which the file is stored on the disk. A path to the file's directory can optionally be included. - Put the variable name (referred to as internal name) given to the file stream to the left of the insertion or extraction operator, the same way you used cin our cout statements
Here is an example program that reads four floating point data values from a file and writes to another file in the reverse order.
Each file in your program has both an internal name and an external name.
The internal name is what you call it in your program; the external name is
the name the operating system knows it by. Somehow, these two names must be
associated with one another. This association is called binding and is
done in function .open()
. Notice that inData
and
outData
are identifiers in the program; "inputfile.txt
" and "outputfile.txt
" are
character strings. inputfile.txt
is the name that was used when the input data
file was created; outputfile.txt
is the name of the file where the answers
are stored.
You can use a basic text editor like Notepad on Windows, or nano text editor to create the input data file according the requirement of the data type and format in your program. The input data file must exist and contain correct data. Otherwise, the input will fail.
Most Desktop IDEs will let you create, add, view and edit input and output files as part of the project. Your lab instructor will show you how to do this with their IDE, and there are links to video examples for our other supported IDEs in the exercises.
For example, in the preceding IODemo program, the input file should look like this:
5.5 6.6 7.7 8.8
You may run the program and experience how File I/O works. You will find the results in output.txt
. You can open it with a simple editor or add it to your project much
like input files.