【问题标题】:C - Reading file content even after the file is deletedC - 即使在文件被删除后读取文件内容
【发布时间】: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


【解决方案1】:

它取决于操作系统/实现。在 Linux 上,该文件实际上是“待删除”,这意味着由于文件已打开,内核“等待”文件关闭,然后才真正释放文件占用的空间。

lsof(也许扩展sleep给你时间去做)

lsof | grep file

表明您的程序进程维护着打开的文件 (lsof man page)。

【讨论】:

    【解决方案2】:

    删除文件并不一定真的“删除”它。发生的事情是对文件的引用被破坏了。它有点像指针。您可以将您的代码与此进行比较:

    void delete(int ** ptr)
    {
        *ptr=NULL;
    }
    
    int main()
    {
        int a=5;
        int p1=&a;
        int p2=&a;
        delete(p1);  // Pretty much equivalent to deleting a file
        printf("a: %d\n", *p1);  // We can still access it through a another pointer
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 2017-03-02
      • 2015-05-05
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多