Pregunta

Is there a way to get the fstream to throw an exception when it fails to open a file, and how would I do this?

I know about the std::fstream.exceptions() method and how to assign bits to it, but what 'bit' would throw the exception?

¿Fue útil?

Solución

Iostreams can be any of three different failure states: fail, bad, and eof. The documentation shows you clearly how to cause any one of those to throw an exception; by default, none of them do, but evaluating a stream object in a boolean context returns false if any of the failure modes have occured.

Example:

#include <fstream>

std::ifstream infile;
infile.expections(std::ios::failbit);
infile.open("foo.txt");    // throws on failure

Otros consejos

When you open a file and it fails, comparing the stream such as

if(mystream==false)
{
//File wasn't opened properly
throw openFailed
}

If you detect that the stream is false, throw an exception you wrote yourself.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top