Nei*_*ran 2 c windows file edit overwrite
我有一个文本文件,我想通过将其重写为临时文件然后覆盖原始文件来对其进行编辑。这段代码并没有这样做,因为它被简化了,但它确实包含了我遇到的问题。在 Windows 上,当重命名功能失败时,Example.TXT 文件将在看似随机的运行次数后消失。我不知道为什么,但到目前为止它在 Linux 上运行良好。为什么会发生这种情况,我该如何从完全不同的方向解决它,例如从程序中覆盖原始文件而不重命名?
此外,还有哪些其他更好的方法?这种方法在Windows上还有其他缺陷,比如在调用remove之后重命名之前用户关闭了程序,这在Linux上不会有问题(摆脱remove之后)?
#include <stdio.h>
#include <assert.h>
int main(int argc, char *argv[]) {
unsigned int i=0;
FILE *fileStream, *tempStream;
char fileName[] = "EXAMPLE.TXT";
char *tempName = tmpnam(NULL);
while(1) {
printf("%u\n",i++);
assert(fileStream = fopen(fileName, "r+"));
assert(tempStream = fopen(tempName, "w"));
fprintf(tempStream,"LINE\n");
fflush(tempStream); /* fclose alone is enough on linux, but windows will sometimes not fully flush when closing! */
assert(fclose(tempStream) == 0);
assert(fclose(fileStream) == 0);
assert(remove(fileName) == 0); /* windows fails if the file already exists, linux overwrites */
assert(rename(tempName,fileName) == 0);
}
}
Run Code Online (Sandbox Code Playgroud)
这样做确实很容易造成麻烦。您的代码在 Windows 上有四种可能的结果:
顺便说一句,最后一颗子弹的可能性很大,它当然可以解释可重复的失败。你需要一个更具防御性的策略来处理第二个子弹:
这是一个很常见的场景,winapi 有一个函数ReplaceFile()。请务必使用备份文件选项以获得最大的收益。——