Search code examples
c++while-loopfstreamifstreamfile-processing

Loop to check existence of file and process it


I am starting the first part of a school assignment and I must prompt the user to enter a filename, check for the existence of the file, and if it exists, open it for processing; otherwise I am to have the user enter another filename.

When I compile and run my program below, I get the error message "No file exists. Please enter another filename." When I type in names of files that don't exist it just runs the first part of my do while loop again. I'm a beginner at C++ but I've done this before and I feel as if it should be running properly. Any help would be appreciated.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

struct customerData
{ 
  int _customerID;
  string _firstName, _lastName;
  double _payment1, _payment2, _payment3;
};

void processFile();

int main()
{
  processFile();

  system ("pause");
  return 0;
}

void processFile()
{
  string filename;
  ifstream recordFile;

 do
 {
    cout << "Please enter a filename\n";
    cin >> filename;
    recordFile.open(filename);
    if (recordFile.good())
    // {
    //  enter code for if file exists here
    // }
    ;
 }
 while(recordFile.fail());
 {
        cout << "No file by that name. Please enter another filename\n";
        cin >> filename;
        recordFile.open(filename);
 }
}

Solution

  • To check whether a file was successfully opened you must use the std::fstream::is_open() function, like so:

    void processfile ()
    {
      string filename;
    
      cout << "Please enter filename: ";
      if (! (cin >> filename))
        return;
    
      ifstream file(filename.c_str());
      if (!file.is_open())
      {
        cerr << "Cannot open file: " << filename << endl;
        return;
      }
    
      // do something with open file
    }
    

    The member functions .good() and .fail() check for something else not whether the file was opened successfully.