Here is an example program that reads four floating point data values from a file and writes to another file in the reverse order.
// Program IODemo demonstrates how to use files
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << fixed << showpoint;
//sets all printout in decimal format with decimal points appearing
float val1, val2, val3, val4; // declares 4 variables
ifstream inData; // declares input stream
ofstream outData; // declares output stream
inData.open("inputfile.txt");
// binds program variable inData to the input file "inputfile.txt"
outData.open("outputfile.txt");
// binds program variable outData to the output file "outputfile.txt"
inData >> val1 >> val2 >> val3 >> val4; // inputs 4 values
outData << val4 << endl;
outData << val3 << endl;
outData << val2 << endl;
outData << val1 << endl; // outputs 4 values
return 0;
}
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 will need to use the pico or vi 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.
For example, in the preceding IODemo program, the input file should look like this:
5.5 6.6 7.7 8.8You may run the program and experience how File I/O works.
Copyright: Department of Computer Science, University of Regina.