Open file to read in a function - C++ File Stream

C++ examples for File Stream:File Operation

Description

Open file to read in a function

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int getOpen(ofstream&);
void inOut(ofstream&);
int main()/* w  ww .j a v  a  2 s . com*/
{
   ofstream outFile;
   getOpen(outFile);    // open the file
   inOut(outFile);      // write to it
   return 0;
}
int getOpen(ofstream& fileOut)
{
   string name;
   cout << "\nEnter a file name: ";
   getline(cin,name);
   fileOut.open(name.c_str());   // open the file
   if (fileOut.fail())   // check for successful open
   {
      cout << "Cannot open the file" << endl;
      exit(1);
   }
   else
      return 1;
}
void inOut(ofstream& fileOut)
{
      const int NUMLINES = 5;  // number of lines
      int count;
      string line;
      cout << "Please enter five lines of text:" << endl;
      for (count = 0; count < NUMLINES; ++count)
      {
         getline(cin,line);
         fileOut << line << endl;
      }
      cout << "\nThe file has been successfully written.";
      return;
}

Result


Related Tutorials