Search code examples
c++ifstream

What Is Throwing The Exception In This File Stream?


I don't understand what is throwing the exception here with my input file stream. I have done almost the exact thing before without any problems.

std::string accnts_input_file = "absolute_path/account_storage.txt";
std::string strLine;
std::ifstream istream;
istream.exceptions( std::ifstream::failbit | std::ifstream::badbit );

try
{
    istream.open( accnts_input_file.c_str() );

    while( std::getline( istream, strLine ) )
    {
        std::cout << strLine << '\n';
    }

    istream.close();
}
catch( std::ifstream::failure &e )
{
    std::cerr << "Error opening/reading/closing file" << '\n'
              << e.what()
              << std::endl;
}

I only have it printing the line it reads right now to try and track the error. It reads the file, line by line and prints them, then it throws the exception. The exception says basic_ios::clear, which i don't understand. I think it is ifstream::failbit that is throwing the exception, because when I only set ifstream::badbit it doesn't throw an exception, but I can't figure out why. I've also tried 'while( !istream.oef() )', and most other methods, instead of 'while( std::getline( istream, strLine ) )', but i keep getting the same error.

I'm sure it's probably something obvious I'm missing, but any help would be appreciated. Thanks


Solution

  • From this std::getline reference:

    ...
    a) end-of-file condition on input, in which case, getline sets eofbit.
    ...
    3) If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns.

    That means that on end of file condition, the function sets both eofbit and failbit. And as you asked to get an exception when failbit is set, the library throws an exception.