仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
Is it sufficient to only catch exceptions to detect all binary file read/write errors in C++?
在下面的示例中,设置了文件异常。在Try-Catch块内部,正在使用gcout()
函数验证读取数据的大小。设置异常时是否有必要测试gcount()
的返回值?
#include <iostream>
#include <fstream>
int main()
{
char buf[100];
std::ifstream file;
file.exceptions(std::ios_base::badbit | std::ios_base::failbit | std::ios_base::eofbit);
try {
file.open("file.bin", std::ios_base::in | std::ios_base::binary);
file.read(buf, sizeof buf);
// Is this error check redundant?
if (file.gcount() != sizeof buf) {
std::cout << "gcount(): Read errorn";
}
file.close();
} catch (...) {
std::cout << "Exception: Read errorn";
}
return 0;
}
read()
完全保证 gcount()
不能等于所需的缓冲区大小的事实。您可以在A 成功 read()
之后查看gcount()
,以检查其实际读取的字节数量,如果抛出异常,则不是这种情况。
在您的示例中,您设定了一个例外,以便在read()
的所有可能结果上都抛出了不读取整个请求大小的结果。因此,是的,在这种情况下,检查gcount()
是多余的。如果到达EOF,请检查gcount()
只有例外,您想知道读取了多少个字节才有意义。对于 binary 读取,除非数据是可变长度,否则您根本不知道它的大小。如果您需要处理以EOF结尾的数据,则不应在eofbit
上抛出异常。仅当EOF是一个真实的错误条件时,就将异常放置(即,流的末尾的数据不完整(。
正确,流异常功能通过类型特征BitmaskType
的std::ios_base::iostate
参数传递。BitMask类型支持所有位运算符:
operator&amp;,运算符|,运算符^,运算符〜,操作员&amp; =,操作员| =和操作员^= = oter^= = = bitMask类型的值,并且与相应的内置运算符具有相同的语义如果位于bitmask元素是两个的独特整数功能,则在未签名的整数上会有。
相关文章:
- C++-从文本文件读取矢量错误
- 增加 gil 读取图像错误
- C++访问冲突读取位置错误
- 使用DPI从C 函数中从SV中的读取值错误
- 使用 valgrind 时获得 int 变量指针的无效读取大小错误
- 使用 valgrind 的地图中的读取大小错误无效
- 瓦尔格林德无效读取大小 4 错误
- 无法修复访问冲突读取位置错误
- 为什么开始读取返回错误ENOMEM(_B)
- 如何修复访问冲突读取位置错误
- 从Android Java读取二进制错误UE4-C++
- VS 2012 调试 处理<文件时出现意外的符号读取器错误.exe>
- 处理 POSIX 套接字读取() 错误
- C、Linux 中的串行端口读取/打开错误
- C++:std::复制失败,出现访问冲突读取位置错误
- 从文本文件/文本流中读取Q字符串错误
- C++“访问冲突读取位置”错误
- (Qt)在尝试使用MainWindow上另一个小部件类的任何函数时出现读取访问错误
- read()返回在某些系统上读取的错误字节数
- 在c++中读取文件错误