#include<stdio.h>
#include<fcntl.h> //open
#include<unistd.h> //close read write
#include<stdlib.h> //exit
#include<errno.h> //perror
#define buffer_size 1024
int main(int argc ,char **argv)
{
int from_fd,to_fd;
int bytes_read,bytes_write;
char buffer[buffer_size];
char *ptr = NULL;
if(3 != argc)
{
printf("need from file and to file\n");
exit(0);
}
if((from_fd = open(argv[1],O_RDONLY)) == -1 )
{
perror("open from file error!\n");
exit(-1);
}
if( (to_fd = open (argv[2],O_WRONLY | O_CREAT ,0777)) == -1)
{
perror("open to file error!\n ");
close(from_fd);
exit(-1);
}
while(bytes_read = read(from_fd,buffer,buffer_size))//从from_fd文件读buffer_size长度的字节到buffer缓冲区
{
if(-1 == bytes_read)//未读取到
{
break;
}
else if(bytes_read > 0)//读取到
{
ptr=buffer;
while(bytes_write = write(to_fd,buffer,bytes_read))//将缓冲区bytes_read长度的字节写入to_fd文件
{
if(-1 == bytes_write)//写入失败
{
perror("write error!\n");
break;
}
else if(bytes_write == bytes_read)//全部写入
{
break;
}
else//部分写入
{
bytes_read=bytes_read-bytes_write;
ptr=ptr+bytes_write;
}
}
if(-1 == bytes_write)
{
perror("write error!\n");
break;
}
}
}
close(from_fd);
close(to_fd);
return 0;
}
linux系统调用--复制一个文件
最新推荐文章于 2024-11-12 23:07:13 发布