c++ - `fwrite` 不害怕 't work directly after ` 吗?

标签 c++ windows file-io stdio

我有一个使用 stdio 读写二进制文件的程序。它缓存当前流位置,如果读/写偏移量已经在所需位置,则不会查找。

然而,一个有趣的问题出现了,即当读取一个字节并写入后续字节时,它实际上并没有被写入!

这是一个重现问题的程序:

#include <cstdio>

int main() {
    FILE *f = fopen("test.bin", "wb");
    unsigned char d[1024] = { 0 };
    fwrite(d, 1, 1024, f);
    fclose(f);
    f = fopen("test.bin", "rb+");
    for (size_t i = 0; i < 1024; i++) {
        unsigned char a[1] = { 255 - (unsigned char)(i) };
        fflush(f);
        fwrite(a, 1, 1, f);
        fflush(f);
        fseek(f, i, SEEK_SET);
        fread(a, 1, 1, f);
        printf("%02X ", a[0]);
    }
    fclose(f);
    return 0;
}

您应该看到它写入字节 FF下降到 00 ,但是只写入第一个字节,因为它不跟在 fread 之后立即。

如果在fwrite之前寻找, 它的行为正确。

问题发生在 Visual Studio 2010/2012 和 TDM-GCC 4.7.1 (Windows) 上,但它适用于 codepad 我猜这是因为它是在 Linux 上执行的。

知道为什么会这样吗?

最佳答案

C99 §7.18.5.3/6(引自 N869 最终草案):

“When a file is opened with update mode (’+’ as the second or third character in the above list of mode argument values) […] input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.”

关于c++ - `fwrite` 不害怕 't work directly after ` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23843587/

相关文章:

windows - 从 Windows 角度看 x86 程序集?

c++ - C++/WinRT 到底是什么?

php - 合并 2 个非常大的文本文件,更新每一行,不使用内存

java - 如何在不创建文件的情况下打开文件(图像、pdf、utc...)

c++ - 如何像在 std::set 中一样在 std::map 中找到最小值/最大值?

c++ - 使用std::hash <uint64_t>作为自定义类

c++ - 与 vector 调用不匹配

c++ - 将 Struct 对象插入队列时出现问题

python - 在Windows上更改IP地址的脚本

java - java 的 File 类的对象是可序列化的吗?