08 - Input and Output File
08 - Input and Output File
Steps: (1) Open the file (2) Use the file (read from, write to,
or both) (3) Close the file.
File Operations
Requires fstream header file:
use ifstream data type for input files.
use ofstream data type for output files.
use fstream data type for both input, output files.
ifstream:
Open for input only and file cannot be written to.
Open fails if file does not exist.
ofstream:
Open for output only and file cannot be read from.
File created if no file exists.
File contents erased if file exists.
File Operations (cont.)
Can use input file object and >> to copy data from file to
variables:
infile >> partNum;
infile >> qtyInStock >> qtyOnOrder;
Can use eof() member function to test for end of input file.
Closing Files
Use the close() member function:
infile.close();
outfile.close();
int main()
{
fstream infile("input.txt", ios::in); // open the files
fstream outfile("output.txt", ios::out);
int num;
if (!input)
{
cout << "While opening a file an error is encountered" << endl;
return 0;
}
else
cout << "File is successfully opened" << endl;
while(!input.eof())
{
input.getline(str, 80);
cout << str << endl;
}
input.close();
return 0;
}
Example 5: File Operations
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
int num;
ifstream inp("input.txt"); // open the input file
ofstream out("output.txt"); // open the output file
if (!inp.is_open()) // check for successful opening
{
cout << "Input file could not be opened! Terminating!\n;
return 0;
}
while (inp >> num)
out << num * 2 << endl;
inp.close();
out.close();
cout << "Done!" << endl;
return 0;
}