我有一个使用 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/