zoukankan      html  css  js  c++  java
  • 文件的移动,删除 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文件也不会遗留下来。

  • 相关阅读:
    【C#学习笔记】 IDisposable 接口
    【C#学习笔记】 List.AddRange 方法
    Request a certificate from a certificate vendor
    How to install your SSL Certificate to your Windows Server
    How to generate a CSR in Microsoft IIS 7
    我爱你 肖厦
    OAuth2.0协议之新浪微博接口演示
    重写mouseEvent 事件 怎么实现自定义的无边框窗口移动
    原文地址:Qt数据库总结 作者:ImmenseeT
    QT+MySQL图片插入数据库并显示 2013-03-12 13:58:52
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/6340114.html
Copyright © 2011-2022 走看看