【问题标题】:how can i read last 2 bytes from file and delete them after read如何从文件中读取最后 2 个字节并在读取后删除它们
【发布时间】:2012-03-07 10:52:26
【问题描述】:

这里我为CRC 16开发了用于文件验证的程序

在这里我计算了文件的 CRC 16,并在文件末尾写了这个 CRC 值。 crc 值数据类型为unsigned short,因此占用 2 个字节。

代码在这里

void appendCRCtoFile(const char* filePath, unsigned short result) {
        FILE *readFile;
        //open a file for Reading
        readFile = fopen(filePath, "ab");
        fseek(readFile, SEEK_END, SEEK_SET);
        const unsigned char check_bytes[2] = { result >> 8, result & 255 };
        const size_t wrote = fwrite(check_bytes, 1, sizeof(check_bytes), readFile);
        if (wrote == 2) {
            printf("succesfull wrote 2 bytes\n");

        } else {
            printf("Failed to wrote 2 bytes\n");
        }
        fclose(readFile);
    }

现在我必须从文件中读取这最后两个字节,并希望在读取后删除它们并再次计算 CRC。那么如何读取最后两个字节并在读取后删除它们。

【问题讨论】:

  • fseek(readFile, SEEK_END, SEEK_SET); 可能是错误的。改用fseek(readFile, 0, SEEK_END); ...
  • 没有从文件中删除字节的标准方法。您要么必须复制文件(减去不需要的数据),要么使用某些操作系统特定的功能。

标签: c file


【解决方案1】:

如果我理解正确,你想rewind 文件返回两个字节。

fseek(readFile, -2, SEEK_CUR);

【讨论】:

  • 感谢您的回复,它不起作用
猜你喜欢
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多