kijato

File_Stream_Objects_as_Function_Arguments

Apr 29th, 2020
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. bool writeFile (ofstream&, char*);
  6. bool readFile (ifstream&, char*);
  7.  
  8. int main ()
  9. {
  10.    string data;
  11.    bool status;
  12.    ofstream outfile;
  13.    status = writeFile(outfile, "students.dat");
  14.    if (!status)
  15.    {
  16.       cout << "File could not be opened for writing\n";
  17.       cout << "Program terminating\n";
  18.       return 0;
  19.    }
  20.    else
  21.    {
  22.       cout << "Writing to the file" << endl;
  23.       cout << "Enter class name: ";
  24.       getline(cin, data);
  25.       outfile << data<< endl;
  26.       cout << "Enter number of students: ";
  27.       cin >> data;
  28.       cin.ignore();
  29.       outfile << data<< endl;
  30.       outfile.close();
  31.    }
  32.    ifstream infile;
  33.    status = readFile(infile, "students.dat");
  34.    if (!status)
  35.    {
  36.       cout << "File could not be opened for reading\n";
  37.       cout << "Program terminating\n";
  38.       return 0;
  39.    }
  40.    else
  41.    {
  42.       cout << "Reading from the file" << endl;
  43.       getline(infile, data);
  44.       while(!infile.fail())
  45.       {
  46.          cout << data << endl;
  47.          getline(infile, data);
  48.       }
  49.       infile.close();
  50.    }
  51.    return 0;
  52. }
  53.  
  54. bool writeFile (ofstream& file, char* strFile)
  55. {
  56.    file.open(strFile);
  57.    if (file.fail())
  58.          return false;
  59.    else
  60.          return true;
  61. }
  62.  
  63. bool readFile (ifstream& ifile, char* strFile)
  64. {
  65.    ifile.open(strFile);
  66.    if (ifile.fail())
  67.          return false;
  68.    else
  69.          return true;
  70. }
Add Comment
Please, Sign In to add comment