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

一、头文件

#include <unistd.h>

二、函数原型

int unlink(const char *pathname);

三、函数介绍

unlink()函数功能即为删除文件。执行unlink()函数会删除所给参数指定的文件。

注意:

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

返回值:成功返回0,失败返回 -1

四、代码示例

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>

int main(int argc, const char * argv[]) {
    int fd = open("test.txt", O_RDWR | O_TRUNC | O_CREAT, 0664);
    assert(fd != -1);
    if (unlink("test.txt") < 0) {
        printf("unlink errpr!\n");
    }
    char buff[128] = {0};
    write(fd, "hello world!", 12);
    if (lseek(fd, 0, SEEK_SET) == -1) {
        printf("lseek error!\n");
    }
    read(fd, buff, 12);
    printf("%s\n", buff);
    return 0;
}

五、运行结果

hello world!
Program ended with exit code: 0

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

六、函数说明

UNLINK(2)                   BSD System Calls Manual                  UNLINK(2)

NAME
     unlink, unlinkat -- remove directory entry

SYNOPSIS
     #include <unistd.h>

     int
     unlink(const char *path);

     int
     unlinkat(int fd, const char *path, int flag);

DESCRIPTION
     The unlink() function removes the link named by path from its direc-
     tory and decrements the link count of the file which was referenced
     by the link.  If that decrement reduces the link count of the file
     to zero, and no process has the file open, then all resources asso-
     ciated with the file are reclaimed.  If one or more process have the
     file open when the last link is removed, the link is removed, but
     the removal of the file is delayed until all references to it have
     been closed.

     The unlinkat() system call is equivalent to unlink() or rmdir()
     except in the case where path specifies a relative path.  In this
     case the directory entry to be removed is determined relative to the
     directory associated with the file descriptor fd instead of the cur-
     rent working directory.

     The values for flag are constructed by a bitwise-inclusive OR of
     flags from the following list, defined in <fcntl.h>:

     AT_REMOVEDIR
             Remove the directory entry specified by fd and path as a
             directory, not a normal file.

     If unlinkat() is passed the special value AT_FDCWD in the fd parame-
     ter, the current working directory is used and the behavior is iden-
     tical to a call to unlink or rmdir respectively, depending on
     whether or not the AT_REMOVEDIR bit is set in flag.

RETURN VALUES
     Upon successful completion, a value of 0 is returned.  Otherwise, a
     value of -1 is returned and errno is set to indicate the error.

ERRORS
     The unlink() system call will fail if:

     [EACCES]           Search permission is denied for a component of
                        the path prefix.

     [EACCES]           Write permission is denied on the directory con-
                        taining the link to be removed.

     [EBUSY]            The entry to be unlinked is the mount point for a
                        mounted file system.

     [EBUSY]            The file named by the path argument cannot be
                        unlinked because it is being used by the system
                        or by another process.

     [EFAULT]           Path points outside the process's allocated
                        address space.

     [EIO]              An I/O error occurs while deleting the directory
                        entry or deallocating the inode.

     [ELOOP]            Too many symbolic links are encountered in trans-
                        lating the pathname.  This is taken to be indica-
                        tive of a looping symbolic link.

     [ENAMETOOLONG]     A component of a pathname exceeds {NAME_MAX}
                        characters, or an entire path name exceeds
                        {PATH_MAX} characters (possibly as a result of
                        expanding a symlink).

     [ENOENT]           The named file does not exist.

     [ENOTDIR]          A component of the path prefix is not a direc-
                        tory.

     [EPERM]            The named file is a directory and the effective
                        user ID of the process is not the super-user.

     [EPERM]            The directory containing the file is marked
                        sticky, and neither the containing directory nor
                        the file to be removed are owned by the effective
                        user ID.

     [EROFS]            The named file resides on a read-only file sys-
                        tem.

     In addition to the errors returned by the unlink(), the unlinkat()
     may fail if:

     [EBADF]            The path argument does not specify an absolute
                        path and the fd argument is neither AT_FDCWD nor
                        a valid file descriptor open for searching.

     [ENOTEMPTY]        The flag parameter has the AT_REMOVEDIR bit set
                        and the path argument names a directory that is
                        not an empty directory, or there are hard links
                        to the directory other than dot or a single entry
                        in dot-dot.

     [ENOTDIR]          The flag parameter has the AT_REMOVEDIR bit set
                        and path does not name a directory.

     [EINVAL]           The value of the flag argument is not valid.

     [ENOTDIR]          The path argument is not an absolute path and fd
                        is neither AT_FDCWD nor a file descriptor associ-
                        ated with a directory.

SEE ALSO
     close(2), link(2), rmdir(2), symlink(7)

STANDARDS
     The unlinkat() system call is expected to conform to POSIX.1-2008 .

HISTORY
     An unlink() function call appeared in Version 6 AT&T UNIX.  The
     unlinkat() system call appeared in OS X 10.10

4th Berkeley Distribution        June 4, 1993        4th Berkeley Distribution
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345