C语言文件拷贝,busybox

从busybox中扣出来的文件拷贝和移动的实现源码

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

int copy_file( const char *souse, const char *dest )
{
    int ret = 0;
    int souse_fd= -1, dest_fd= -1;
    struct stat statbuff;

    do{
        if( stat( souse, &statbuff) < 0){
            printf("stat( %s ) error : %s\n", souse, strerror(errno) );
            ret = -1;
            break;
        }

        souse_fd = open( souse, O_RDONLY );
        if( souse_fd <= 0 ){
            printf("open( %s, O_RDONLY ) error : %s\n", souse, strerror(errno) );
            ret = -1;
            break;
        }
        dest_fd = open( dest, O_WRONLY|O_CREAT|O_EXCL, 0666 );
        if( dest_fd <= 0 ){
            printf("open( %s, O_WRONLY|O_CREAT|O_EXCL, 0666 ) error : %s\n", dest, strerror(errno) );
            ret = -1;
            break;
        }

        ret = sendfile( dest_fd, souse_fd, NULL, statbuff.st_size );
        if( ret < 0 )
            printf("sendfile( %s, %s ) error : %s\n", souse, dest, strerror(errno) );
    }while(0);

    if( souse_fd > 0 )
        close( souse_fd );
    if( dest_fd >0 )
        close( dest_fd );

    sync();


    return ret;
}

int move_file( const char *souse, const char *dest )
{
    return ( ( copy_file( souse, dest ) >= 0 ) && ( unlink( souse ) == 0 ) );
}

int main()
{
    copy_file( "./sounse_file", "./copy_file" ); 
    move_file( "./sounse_file", "./move_file" );
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值