Search code examples
c++ifstream

Checking ifstream, doesn't work after an error?


I've attached my code below. If I remove the if statement to check if the file is opened, this sequence will work. Why won't it work with the if statement? Also, it works as written below if I supply the correct file name the first time. It only hangs up if I enter an incorrect file name first.

Thanks for the help!

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream inputFile(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}

Solution

  • The code you show is perfectly legal, so I suppose that you use inputFile after this "bad filename" logic:

    ifstream inputFile(fileName.c_str());
    
    if(!inputFile)
    {
        cout << "Unable to locate input file, please ensure it is in the working directory"
             << endl;
        cout << "Enter the name of your input file (ex. input.txt):  ";
        cin >> fileName;
        cout << endl;
    
        ifstream inputFile(fileName.c_str());
    }
    else
    {
        cout << "Input file opened successfully!" << endl;
    }
    // USING inputFile here
    

    The problem with that is, that you still have the original inputFile here. The inputFile inside of the if statement is a new std::ifstream. It may be easier to see if you use a different name:

    ifstream inputFile(fileName.c_str());
    
    if(!inputFile)
    {
        cout << "Unable to locate input file, please ensure it is in the working directory"
             << endl;
        cout << "Enter the name of your input file (ex. input.txt):  ";
        cin >> fileName;
        cout << endl;
    
        ifstream differentInputFile(fileName.c_str()); //HERE
    }
    else
    {
        cout << "Input file opened successfully!" << endl;
    }
    

    The correct way to close the bad file and reopen with the correct file name is:

    inputFile.close();
    inputFile.open(fileName.c_str());
    

    The complete code then becomes

    ifstream inputFile(fileName.c_str());
    
    if(!inputFile)
    {
        cout << "Unable to locate input file, please ensure it is in the working directory"
             << endl;
        cout << "Enter the name of your input file (ex. input.txt):  ";
        cin >> fileName;
        cout << endl;
    
        inputFile.close();
        inputFile.open(fileName.c_str());
    }
    else
    {
        cout << "Input file opened successfully!" << endl;
    }
    

    It's also advisable to enable warnings. My recommendation is to use -Wall -Wextra -Wshadow -pedantic -Wfatal-errors (that's for gcc and clang).