문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top