c语言unlink函数 c语言unlink函数失败原因

C语言基础-unlink函数的使用

注意:

站在用户的角度思考问题,与客户深入沟通,找到饶河网站设计与饶河网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站制作、成都网站设计、企业官网、英文网站、手机端网站、网站推广、域名与空间、网页空间、企业邮箱。业务覆盖饶河地区。

执行unlink()函数并不一定会真正的删除文件,它先会检查文件系统中此文件的连接数是否为

1,如果不是1说明此文件还有其他链接对象,因此只对此文件的连接数进行减1操作。若连接数为1,并且在此时没有任何进程打开该文件,此内容才会真正地被删除掉。在有进程打开此文件的情况下,则暂时不会删除,直到所有打开该文件的进程都结束时文件就会被删除。

从结果可以得出,在文件打开的情况下unlink()并不会立即删除,并且对文件依然可以进行读写操作,在进程结束之后文件就会被删除掉!

unlink在c语言中的使用

功 能: 删掉一个文件

用 法: int unlink(char *filename);

程序例:

#include stdio.h

#include io.h

int main(void)

{

FILE *fp = fopen("junk.jnk","w");

int status;

fprintf(fp,"junk");

status = access("junk.jnk",0);

if (status == 0)

printf("File exists\n");

else

printf("File doesn't exist\n");

fclose(fp);

unlink("junk.jnk");

status = access("junk.jnk",0);

if (status == 0)

printf("File exists\n");

else

printf("File doesn't exist\n");

return 0;

}

C语言unlink函数

这个提问说明了两个问题

你不会查手册,命令man 2 unlink有这个函数详细的说明

你不了解Linux的文件系统

unlink的文档是这样描述的:

unlink()  deletes  a  name  from  the  filesystem.  If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.

If the name was the last link to a file but any processes still have the file open the file will remain in existence  until  the  last  file descriptor referring to it is closed.

If the name referred to a symbolic link the link is removed.

If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.

首先你要明确一个概念,一个文件是否存在取决于它的inode是否存在,你在目录里看到的是目录项里一条指向该inode的链接,而不是文件的本身.

当你调用unlink的时候他直接把目录项里的该条链接删除了,但是inode并没有动,该文件还是存在的,这时候你会发现,目录里找不到该文件,但是已经打开这个文件的进程可以正常读写.只有当打开这个inode的所有文件描述符被关闭,指向该inode的链接数为0的情况下,这个文件的inode才会被真正的删除.

从unlink的名字上就应该能判断出来,unlink含义为取消链接,remove才是删除的意思


分享文章:c语言unlink函数 c语言unlink函数失败原因
本文网址:http://lszwz.com/article/dooeced.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款