检查 istream::read 和 istream::seekg 失败的最佳方法



假设我有以下代码:

std::ifstream file(name, flags);
file.seekg(0, std::ios::beg);
// Check for error
file.read(buffer, size);
// Check for error

检查错误查找/读取的最干净方法是什么?我应该只检查ios::fail和ios::bad bit吗?这些失败会触发异常吗?(我相信您必须手动注册失败异常(

当这两个函数失败时,它们会在错误掩码中设置某些标志,您可以在 if 语句中检查这些标志。流的布尔转换运算符将检查掩码中是否有failbitbadbit,如果两者都未设置,则将返回 true。默认情况下,不会引发异常,但可以使用 exceptions() 方法设置异常。

if (!file.seekg(0, std::ios::beg)) {
  // Check for error
}
if (!file.read(buffer, size)) {
  // Check for error
}
您可以使用

::std::iostream::exceptions方法使其在相应检查失败时自动触发异常:

file.exceptions(::std::ios_base::failbit | ::std::ios_base::badbit | ::std::ios_base::eofbit);
file.seekg(0, std::ios::beg); // will throw std::ios_base::failure if fails
file.read(buffer, size); // will throw std::ios_base::failure if fails

最新更新