从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;
}