File I/O
#include <iostream.h>
and #include <fstream.h>
ifstream inData;
ofstream outData;
inData.open("file_input.txt");
outData.open("file_output.txt");
    if (!inData)
       {
       cout << "** Problem: cannot open file_input.txt, ending program."
	    << endl;
       return 1;
       }
Note that this step is not mandatory, but it is
good programming practice.
inData >> inVar1 >> inVar2;
outData << inVar1;     
The following C++ program illustrates file I/O with simple error checks after the open statements.
/****************************************************
*
*  FileName:	~ftp/pub/class/cplusplus/Csyntax-files/Cpgms/file_io.cpp
*  Author:	Ada Lovelace
*  Purpose:
*		Demonstrate simple file I/O 
*
********************************************************/
#include <iostream.h>
#include <fstream.h>
#include <string>
using namespace std;
int main() {
    ifstream inData;
    ofstream outData;
    string inVar1;
    string inVar2;
    cout << endl << "This program reads from an input file, file_input.txt,"
	 << endl << " and writes to an output file, file_output.txt" << endl;
    inData.open("file_input.txt");
    if (!inData)
       {
       cout << "** Problem: cannot open file_input.txt, ending program."
	    << endl;
       return 1;
       }
    outData.open("file_output.txt");
    if (!outData)
       {
       cout << "** Problem: cannot open file_output.txt, ending program."
	    << endl;
       return 1;
       }
    inData >> inVar1 >> inVar2;
    while ( inData)
       {
       outData << inVar2;     // output in reverse order
       outData << " ";
       outData << inVar1;     
       outData << endl;     
       inData >> inVar1 >> inVar2;
       } // end while
    
    inData.close();
    outData.close();
} // end main
This page has been accessed  
   times.
Last modified: Friday, 21-Aug-2020 15:28:13 CST
Copyright 2000 Department of Computer Science, University of Regina.