【发布时间】:2017-11-27 03:05:47
【问题描述】:
检查这个程序。
#include <stdio.h>
int main() {
FILE* f;
char x[100];
f = fopen("a.txt","r");
int a = remove("a.txt");
sleep(5);
fgets(x,100,f);
printf("Remove() : %d\nFile Content : %s\n",a,x);
printf("fclose() : %d\n",fclose(f));
return 0;
}
在上面的代码中,文件在读取内容之前就被删除了。但它仍然可以正常工作并以状态 0 成功关闭文件。
输出
$ echo hello > a.txt
$ gcc a.c && ./a.out
Remove() : 0
File Content : hello
fclose() : 0
【问题讨论】:
-
因为所有数据都加载到了内存中,所以删除文件不会有什么问题~
-
stackoverflow.com/questions/9132737/… Read answer by Alexander Pavlov.. 它说
fopen()只创建文件句柄。 -
您的查询/问题是什么,您想要达到什么目的?
-
只是想知道为什么可以这样做。
-
如果你想在阅读或打开文件之前删除文件,你需要在
open之前调用remove。当前实现文件的内容已经在 RAM 中,所以它的预期行为。
标签: c