C - 即使在删除文件后也读取文件内容

时间:2017-11-27 03:05:47

标签: c

检查此程序。

#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

2 个答案:

答案 0 :(得分:2)

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

执行# Creating a socket try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print "Socket created!" #Binding the socket to specified ports try: sock.bind((ownhost, ownport)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' # Listening for incoming requests sock.listen(10) print 'Socket now listening' conn, addr = sock.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) # Handling the incoming requests received req = conn.recv(1024) reqpro = req.split('|') # If the request is a join request if reqpro[0] == "JOIN": func1(reqpro, arg2) elif (reqpro[0] == 'UPDATE') and (reqpro[1] == 'PRED'): func2(reqpro,arg2) else: print "invalid request type" sys.exit() (可能会延长lsof以给你时间)

sleep

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

答案 1 :(得分:1)

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

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
}