检测不完整的 32 位二进制数据

detect incomplete 32 bit binary data

我有一个二进制文件,我需要从中读取 32 位模式 - 如果达到 EOF 使其少于 32 位 - 我需要出错,说意外的 eof else 只是中断。我尝试了很多,但我无法让不完整的字节检测部分正常工作。有人可以提供一些如何实现它的指针吗?我确实考虑过一次探索一个字节 byte[0] 并评估其 EOF 是否有效但没有用。

   for (;;)
   {
     bytes_read = fread(buffer, 4, 1, inFile);
     if (bytes_read == 1)
     {
      // perform the task
     }
     else
     {
         // detect if its incomplete sequence or EOF and output appropriately
     }
   }

P.S : 根据评论编辑 fread -

fread 不是 return 读取的字节数,而是 return 读取的项目数,其大小在第二个参数中给出。由于您要求它阅读 1 项;如果它在读取项目的所有字节之前遇到 EOF,它应该 return 0.

虽然 sizeof(char) 被定义为 1,但在您实际指的不是某物大小的上下文中使用它是不合适的。在这种情况下,它只是一个计数,所以你应该使用 1.

size_t items_read = fread(buffer, sizeof(unsigned long), 1, inFile);
if (items_read == 1) {
    // perform the task
} else if (feof(inFile)) {
    // got EOF before reading the last number
} else if (ferror(inFile)) {
    // got an error
}

您的代码告诉 fread 从文件中读取一条包含 4 个字节的记录。如果记录不完整,则会return0(0条记录读取,错误)。如果记录丢失(在文件末尾),它也会return 0(读取0条记录,正常情况)。您必须调整代码以区分这些情况,改为使用 fread return 4(字节)。

如果无法读取文件末尾的 4 个字节,您希望 fread 输出小于 4。要有此行为,您应该告诉 fread 以 1 个字节为单位读取:

bytes_read = fread(buffer, 1, 4, inFile);

再看人数:

if (bytes_read == 4)
{
    // perform the task
}
else if (bytes_read > 0)
{
    // bad file format - not a multiple of 4 bytes
}
else if (bytes_read == 0)
{
    break; // success
}
else // bytes_read = -1
{
    // general file error
}