我在 Windows 上遇到文件写入失败的一些问题。我将其简化为以下示例:
FILE* f = fopen("test.out", "r+b");
fseek(f, -1, SEEK_END); // one byte before the end
printf("read byte: %c\n", fgetc(f)); // read the last byte; now at the end
printf("attempting write: %d\n", fputs("text", f));
这会正确输出 的最后一个字节test.out
,但fputs
失败并返回 -1。这些类似的例子都可以正常工作:
不要阅读
FILE* f = fopen("test.out", "r+b"); fseek(f, 0, SEEK_END); // this is where I ended up after the fgetc() above printf("attempting write: %d\n", fputs("text", f));
读完就追到底(即使我们已经在那里了)
FILE* f = fopen("test.out", "r+b"); fseek(f, -1, SEEK_END); printf("read byte: %c\n", fgetc(f)); fseek(f, 0, SEEK_END); printf("attempting write: %d\n", fputs("text", f));
寻找我们已经在哪里
FILE* f = fopen("test.out", "r+b"); fseek(f, -1, SEEK_END); printf("read byte: %c\n", fgetc(f)); fseek(f, ftell(f), SEEK_SET); printf("attempting write: %d\n", fputs("text", f));
读取,但不是最后一个字节
FILE* f = fopen("test.out", "r+b"); fseek(f, -2, SEEK_END); // two bytes before the end printf("read byte: %c\n", fgetc(f)); // read the penultimate byte printf("attempting write: %d\n", fputs("text", f));
读到最后(...)
FILE* f = fopen("test.out", "r+b"); fseek(f, -1, SEEK_END); // one byte before the end printf("read byte: %c\n", fgetc(f)); // read the last byte; now at the end printf("read byte: %c\n", fgetc(f)); // read a garbage byte printf("attempting write: %d\n", fputs("text", f));
这些似乎都表明流错误或 eof 问题,但ferror(f)
都feof(f)
返回 0 直到 failed fputs()
。之后,ferror(f)
非零,但errno
为0,所以我不知道问题出在哪里
我只在 Windows 上看到这一点,在 Visual Studio 2008 和 GCC 4.7.2 (MinGW) 中。在 Linux 上,相同的代码运行没有错误