在Windows中通过随机重命名覆盖文件失败 [英] Overwriting files in Windows by renaming randomly fails

查看:141
本文介绍了在Windows中通过随机重命名覆盖文件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要编辑的文本文件,方法是将其重写为临时文件,然后覆盖原始文件.这段代码并没有这样做,因为它已经简化了,但确实包含了我遇到的问题.在Windows上,当重命名功能失败时,EXAMPLE.TXT文件将在随机运行几次后消失.我不知道为什么,但是到目前为止,它在Linux上运行良好.为什么会发生这种情况?我该如何解决它的完全不同的方向,例如在不重命名的情况下从程序内部覆盖原始文件?

I have a text file that I want to edit by rewriting it to a temp file and then overwrite the original. This code doesn't do that as it's simplified but it does include the problem I have. On Windows the EXAMPLE.TXT file will disappear after a seemly random number of runs when the rename function fails. I don't know why but so far it has worked fine on Linux. Why does this happen and how can I solve it going in an entirety different direction, such as overwriting the original file from within the program without renaming?

此外,还有哪些其他更好的方法?这种方法在Windows上还有其他缺陷,例如,在调用remove之后但在重命名之前,用户正在关闭程序,这在Linux上(摆脱了remove之后)不是问题吗?

Furthermore, what other, better methods exist? This method has other flaws on Windows, such as the program being closed by a user just after remove is called but before rename, which would not be a problem on Linux (after getting rid of 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);
  }
}

推荐答案

有时防病毒软件可能会在不方便的时刻扫描文件来引起此类问题.

Sometimes antivirus software can cause such a problem by scanning a file at an inconvenient moment.

如果remove失败,请尝试睡眠片刻,然后重试.

If the remove fails, try sleeping for a short time and then retrying.

这篇关于在Windows中通过随机重命名覆盖文件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆