文件的移动,删除 rename remove unlink 函数

 int rename(const char *oldpath, const char *newpath);

 rename()  renames  a  file,  moving it between directories if required.

利用rename实现简单的mv指令

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>


int main(int argc, char* argv[])
{
    if (argc !=3)
    {
        printf("need old an new file
");
        exit(0);
    }

    if (-1 == rename(argv[1], argv[2]))
    {
        perror("rename");
        exit(0);
    }

    return 0;
}

文件的删除可以使用unlink系统调用。目录的删除可以使用rmdir系统调用。而通用的既能删除文件又能删除目录的系统调用是remove

remove系统调用实际上是在内部封装了unlink和rmdir,当需要删除文件时调用unlink,当需要删除目录时调用rmdir

int unlink(const char *pathname);

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.

 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.

如果文件的链接数为0,但是有进程打开了这个文件,则文件暂不删除,直到打开文件的所有进程都结束时,文件才被删除,利用这点可以确保

即使程序崩溃,它所创建的临时文件也不会遗留下来。

例:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>


int main(int argc, char* argv[])
{
    int fd;
    char buf[30];

    fd = open("mm", O_CREAT|O_RDWR, S_IRWXU);

    unlink("mm");

    write(fd, "temp", 5);
    
    lseek(fd, 0, SEEK_SET);

    read(fd, buf, 5);

    printf("read %s
", buf);

    return 0;
}

最后mm文件被删除了。

程序在创建并打开了文件mm之后,调用了unlink,之后再对文件进行读写操作。

程序如果在unlink之后的代码中出现崩溃,则在程序结束时,temp文件也不会遗留下来。

原文地址:https://www.cnblogs.com/zhangxuan/p/6340114.html