一、unlink
int unlink( const char* pathname);
此函数删除目录项,并将由 pathname 所引用文件的链接计数减 1 。如果还有指向该文件的其它链接,则仍可通过其他链接访问该文件的数据。如果出错,则不对该文件做任何更改。
只有当链接计数达到 0 时,该文件的内容才可被删除。
删除一个文件时,内核首先检查打开该文件的进程数。如果该数达到 0,然后内核检查其链接数,如果这个数也是 0,那么就删除该文件的内容。
#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
int fd;
char buf[20] = {0};
if ((fd =open("tempfile", O_RDWR)) < 0)
printf("open error\n");
if (unlink("tempfile") < 0)
printf("unlink error\n");
printf("file unlinked\n");
read(fd, buf, sizeof(buf));//you could still read this after unlink
printf("%s\n", buf);
sleep(15);
printf("done\n");
exit(0);
}
unlink 的这种性质经常被用来确保即使是在该程序崩溃时,它所创建的临时文件也不会遗留下来。进程用 open 或 create 创建一个文件,然后立即调用 unlink。因为该文件仍旧是打开的,所以不会将其内容删除。只有当进程关闭该文件或终止时(在这种情况下,内核会关闭该进程打开的全部文件),该文件的内容才会被删除。
如果 pahtname 是符号链接,那么 unlink 删除该符号链接,而不会删除由该链接所引用的文件。
二、remove
int remove(const char* pathname);
我们也可以用 remove 函数解除对一个文件或目录的链接。
- 当 remove() 中的 pahtname 指定为目录时,相当于调用 rmdir 删除目录;
- 当 remove() 中的 pathname 指定为文件时,相当于调用 unlink 删除文件链接。
ISO C 指定 remove 函数删除一个文件,这更改了 UNIX 系统历来使用的名字 unlink,其原因是实现 C 标准的大多数非 UNIX 系统并不支持文件链接。
三、总结
unlink:只能删除文件;
remove:可删除目录和文件。
(SAW:Game Over!)