In: Computer Science
(1) Why do several functions in iostream and fstream have identical names? When is it advantageous to reuse function names?
(2) Describe the five-step process of file I/O. Explain how to use ifstream and ofstream to open and close input and output files. Illustrate the process with the skeleton program provided in this section.
Please describe in details.
1.)
2.)
Five step process of file I/O.
Step1: Include
fstream header file.
Step2: Declareobject
of the fstream
or ostream
class to read or write the data to file.
Step3: Open the file
usingopen(filename)
method.
Step4: Check if file exists using fail() function. If file not
exists, then close the file using fclose() function
Step5: Close the file stream object using fclose()
function.
Skeleton c++ program for opening input file stream for reading file
and write the data to output file
stream.
#include <fstream>
using namespace std;
int main()
{
//Open objects of ifstream and ofstream
classes
ifstream inFile;
ofstream outFIle;
//Open file for
reading
inFile.open("input.txt");
//Check if file exists or
not
if (!inFile)
{
cerr <<
"Unable to open file datafile.txt";
exit(1); // call system to stop
}
//Open file for
writing
outFIle.open("output.txt");
//Read data from file inFile and write to
file output.txt
while (inFile >> x)
{
outFile>>x>>endl;
}
//Close the file
objects
inFile.close();
outFile.close();
return 0;
}