linux gnu c 复制文件实例(open,close,creat,read,write)

linux使用open,close,creat,read,write库函数实现文件复制的实例代码如下:

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

// 复制文件,成功返回0,失败返回-1
int copy_file(const char* src_path,const char* dst_path)
{
    if(src_path && dst_path){
        int in,out;
        ssize_t size;
        // TLS变量,减少堆栈占用
        static __thread char buffer[512];
        // 内置函数(nested function),用于函数返回时关闭in,out文件句柄
        int do_return(int code){
            if(-1 == code){
                perror(strerror(errno));
            }
            if(in)
                close(in);
            if(out)
                close(out);
            return code;
        }
        in=open(src_path,O_RDONLY);
        if(-1==in)
        {
            return do_return(-1);
        }
        //S_IRUSR(S_IREAD)  文件拥有者具备读权限
        //S_IWUSR(S_IWRITE) 文件拥有者具备写权限
        //S_IRGRP   用户组具备读权限
        //S_IWGRP   用户组具备写权限
        //S_IXGRP   用户组具备可执行权限
        //S_IROTH   其他用户具备读权限
        // 创建目标文件,并指定合适的权限
        const __mode_t mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH;
        out=creat(dst_path,mode);
        if(-1==out)
        {
            return do_return(-1);
        }
        while(1)
        {
            size=read(in,buffer,sizeof(buffer));
            if(size>0){
                if(-1 == write(out,buffer,size)){
                    return do_return(-1);
                }
            }else if (0 == size){
                break;
            }else if( -1 == size){
                return do_return(-1);
            }
        }
        {
            // 如果目标文件权限与所要求的权限不同则修改文件权限
            struct stat s_buf;
            stat(dst_path,&s_buf);
            if(mode != (s_buf.st_mode & mode)){
                if(-1 == chmod(dst_path,mode)){
                    return do_return(-1);
                }
            }
        }
        return do_return(0);
    }
    return -1;
}

猜你喜欢

转载自blog.csdn.net/10km/article/details/80920732