// Program IODemo demonstrates how to use files
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << fixed << showpoint;
float val1, val2, val3, val4; // declares 4 variables
ifstream inData; // declares input stream
ofstream outData; // declares output stream
// binds program variable inData to file "inputfile.txt"
inData.open("inputfile.txt");
//Testing the state of the stream
//true means the last I/O operation on that stream succeeded
//false means the last I/O operation on that stream failed
if (!inData)
{
cout << "Can't open the input file successfuly." << endl;
return 1;
}
// binds program variable outData to file "outputfile.txt"
outData.open("outputfile.txt");
//Testing the state of the stream
if (!outData)
{
cout << "Can't open the output file successfuly." << endl;
return 2;
}
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;
}
Note that inData and outData are two varibales in the program;
"inputfile.txt" and "outputfile.txt" are character strings.
inputfile.txt is the name of the input data file that we
have created; outputfile.txt is the name of the output data file where
the answers are stored.
If the input file inputfile.txt cannot be found, 1 is returned to the operating system. If the output file outputfile.txt cannot be opened or created, 2 is returned to the operating system. If there is no input and output error, 0 is returned to the operating system. Notice that the main is exited as soon as a value is returned. Therefore, Returning 0 value means normal completion of a program; returning any other value signals an error. When you write your own program, you may choose the value to return to indicate different error conditions.
You can use pico or vi text editor to create the input data file according to the requirement of the data type and format in your program. Input data file must exist and contain correct data. Otherwise, you will get input failure.
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 and test the state of the I/O stream.