文件流的 C++ 操作:何时检查错误?
c++ operations with file streams: when to check for error?
假设我需要对流执行多个读取或写入操作,如果其中任何一个以错误结束,则抛出异常。下面两种方式有什么区别吗:
{
std::ifstream ifs("filename");
int i;
std::string s;
long l;
//all variables are local, so I'm not interested in them in case of exception
//first way
if(!ifs >> i) throw runtime_error("Bad file");
if(!std::getline(ifs, s)) throw runtime_error("Bad file");
if(!ifs >> l) throw runtime_error("Bad file");
//second way
ifs >> i;
std::getline(ifs, s);
ifs >> l;
if(!ifs) throw runtime_error("Bad file");
//do something with variables
}
如果没有区别,那么在类似情况下是否有我应该知道的陷阱?
您可以启用例外:
ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
在这种情况下,如果流无法正确读取某些内容,将抛出 std::ios_base::failure
类型的异常。
假设我需要对流执行多个读取或写入操作,如果其中任何一个以错误结束,则抛出异常。下面两种方式有什么区别吗:
{
std::ifstream ifs("filename");
int i;
std::string s;
long l;
//all variables are local, so I'm not interested in them in case of exception
//first way
if(!ifs >> i) throw runtime_error("Bad file");
if(!std::getline(ifs, s)) throw runtime_error("Bad file");
if(!ifs >> l) throw runtime_error("Bad file");
//second way
ifs >> i;
std::getline(ifs, s);
ifs >> l;
if(!ifs) throw runtime_error("Bad file");
//do something with variables
}
如果没有区别,那么在类似情况下是否有我应该知道的陷阱?
您可以启用例外:
ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
在这种情况下,如果流无法正确读取某些内容,将抛出 std::ios_base::failure
类型的异常。