c++ - C++检测输入是否不满足条件

标签 c++ file c++11 stream istream

更新:请通过清晰的答案和用法示例指导我
我正在从二进制文件中读取数据,其中第一个数字表示要读取的输入或值的数量,第二个数字表示第一个输入的长度,然后是输入本身,之后是第二个输入的长度,然后是输入本身等等。
所以写了下面的代码:

    std::ifstream infile(filename, std::ios_base::binary);
    unsigned int NumberOfInputs;
    infile.read((char *) &NumberOfInputs, sizeof(unsigned int));

    for (unsigned int i = 0; i < NumberOfInputs; i++) {
        unsigned int Input_Lengh;
        infile.read((char *) &Input_Lengh, sizeof(unsigned int));
        string data;
        while (Input_Lengh) {
        char letter;
        infile.read((char *) &letter, sizeof(char));
        data += letter;
        Input_Lengh--;
        }
    }
但是,如果文件已损坏,并且用户告诉我输入的数量是10,而我只读了2个(例如,因为我进入EOF),该怎么办?

最佳答案

使用std::istream::read()时,您可以测试eofbit和failbit标志。当到达文件末尾时,都将同时设置它们。对于您而言,在每次读取操作之后,我建议您测试是否设置了这些标志。如果是这样,只需中断文件读取序列即可。
例如:

if ( (infile.rdstate() & std::ifstream::failbit ) != 0 )
{
/* error handling here*/
}
另外,您可以使用gcount()std::istream方法获取成功读取的字符数。
例如:
if (infile.gcount() < N_EXPECTED_CHARS)
{
    /* error handling here*/
}

关于c++ - C++检测输入是否不满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63355962/

相关文章:

C++ Boost::asio与Arduino的串行通信无法写入

java - 通过不同目录中的 Java 程序运行 Minecraft Launcher?

c++ - 使用 std::enable_if 的正确方法

c++ - 将文件保存在 %temp% 文件夹中?

c - 从同一目录杀死进程

c++ - 在 C++ 中,我可以在定义自己的复制构造函数后跳过定义赋值运算符吗?

c++ - 什么时候需要使用 std::ref ?

c++ - 根据两个角度之间的差异更改值

c++ - 为什么这段代码的输出是fffffff9?

c++ - 如何避免 GDB 中符号的命名空间前缀?