我有一个文本文件,我想通过将其重写为临时文件然后覆盖原始文件来对其进行编辑。这段代码并没有这样做,因为它被简化了,但它确实包含了我遇到的问题。在 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 …Run Code Online (Sandbox Code Playgroud)