代码
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:Jerey_Jobs Version:0.1 Date:
Description:
Funcion List:
*****************************************************/
#include <stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#define BUFFER_SIZE 1024 //缓存区大小
int main(int argc,char ** argv)
{
int from_fd; //原始文件
int to_fd; //目标文件
int bytes_read,bytes_write;//实际读写字节数
char buffer[BUFFER_SIZE];//缓冲区
char *ptr;//数组名不可以改,所以用指针;本身读取所字节型所以用CHAR
if(argc != 3) //0可执行文件文件名(./),1源文件文件名,2是目标文件名
{
printf("usage:from file and to file !\n");
exit(-1);
}
//源文件和目标文件已经输入执行下面程序
from_fd = open(argv[1],O_RDONLY);
if(from_fd == -1) //源文件打开判断
{
perror("open from file fail");//错误处理标志
exit(-1);
}
to_fd = open(argv[2],O_WRONLY | O_CREAT,S_IWUSR | S_IRUSR);//没有则自动创建
if(to_fd == -1) //目标文件打开判断
{
perror("open to file fail");//错误处理标志
exit(-1);
}
while(bytes_read = read(from_fd,buffer,BUFFER_SIZE))//不能保证一次就把文件复制完所以需多次循环
// ,read遇到结束标志的时候为0,表示已经读完;
{
if(bytes_read == -1 && errno != EINTR)//其他原因引起的中断
{
perror("error break!\n");
break;//退出读的操作
}
else if(bytes_read > 0)
{
ptr = buffer;
//解决部分写的问题
while(bytes_write = write(to_fd,ptr,bytes_read))//ptr执行缓存区写的地址,读多少写多少
{
if(bytes_write == -1 && (errno != EINTR))
{
perror("write break!\n");
break;//退出写的操作
}
else if(bytes_write == bytes_read)//写入完毕
{
break;
}
else if(bytes_write > 0)
{
ptr += bytes_write;//往后移动
bytes_read = bytes_write;
}
}
if(bytes_write == -1)
{
break;//退出while循环
}
}
}
close(from_fd);
close(to_fd);
return 0;
}