if ( !file )



  • Gibt es einen Unterschied bei

    std::ifstream file( filename );
    if ( !file )
    

    und

    std::ifstream file( filename );
    if ( !file.is_open() )
    

    ? Bringt es was, beides zu prüfen?



  • #include <fstream>
    #include <iostream>
    
    int main()
    {
    	std::cout << "open\tbool\tgood\tfail\tbad\teof\n";
    	{
    		std::ifstream is{ "file" };
    		std::cout << std::boolalpha << is.is_open() << '\t' << (bool)is << "\t" << is.good() << "\t" << is.fail() << "\t" << is.bad() << "\t" << is.eof() << '\n';
    	}
    	{
    		std::ifstream is{ "not_existing_file" };
    		std::cout << std::boolalpha << is.is_open() << '\t' << (bool)is << "\t" << is.good() << "\t" << is.fail() << "\t" << is.bad() << "\t" << is.eof() << '\n';
    	}
    }
    
    open    bool    good    fail    bad     eof
    true    true    true    false   false   false
    false   false   false   true    false   false
    

    Nö, bringt nichts.



  • Danke 🙂 Und danke für den Hintergrund.

    Obwohl ich gerade merke, brauch ich noch ein wenig, um das richtig zu verstehen.

    Wenn ich jetzt eine Fehlermeldung schreibe, ist das richtig, in beiden Fällen davon auszugehen, das kein solches file existiert?



  • Einen Unterschied gibt es:

    {
    		std::ifstream is{};
    		std::cout << std::boolalpha << is.is_open() << '\t' << (bool)is << "\t" << is.good() << "\t" << is.fail() << "\t" << is.bad() << "\t" << is.eof() << '\n';
    	}
    

    Theoretisch wäre es also besser, is_open zu verwenden.



  • Ich wollte schon fast eine SeppJ-Style Fußbnote über Klugscheißer schreiben ... hätt ichs bloß getan.


Anmelden zum Antworten