#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
#define LEN 30
#define BUF_SIZE 1024
int main(){
int state1;
int state2;
int fp1,fp2;
int len,sourceLen,destLen;
char buf[BUF_SIZE];
char source[LEN],dest[LEN];
//open
printf("input path of source file:\n");
scanf("%s",source);
printf("input path of destination file:\n");
scanf("%s",dest);
printf("cource:%s\n",source);
printf("dest:%s\n",dest);
fp1 = open(source,O_RDONLY);
if(fp1 == -1){
printf("fail to open file!\n");
exit(1);
}
fp2 = open(dest,O_WRONLY|O_CREAT,0755);
if(fp2 == -1){
printf("fail to open file!\n");
exit(1);
}
sourceLen = lseek(fp1,0,SEEK_END); //获取fp1文件的所以内容字节数
lseek(fp1,0,SEEK_SET); //把读写位置移动到开头
//write something
while(1){
len = read(fp1,buf,sizeof(buf)); //获取fp2文件的sizeof(buf)字节数,与实际的len个字节对比
write(fp2,buf,len); //写进len个字节到fp2
if(len < BUF_SIZE){ //内容少于等于sizeof(buf) 循环一次 否则继续读写 直到文件内容全部拷贝完成
break;
}
}
destLen = lseek(fp2,0,SEEK_END); //全部拷贝之后 fp1,fp2的所以内容大小相等,则复制成功
if(sourceLen == destLen){
printf("copy successful!\n");
}else{
printf("source len:%d,dest len:%d\n",sourceLen,destLen);
}
//close
state1 = close(fp1);
if(fp1 == 0){
printf("close successful!\n");
}else if(fp1 == -1){
printf("Erreo:%s,errno:%d\n",strerror(errno),errno);
}
state2 = close(fp2);
if(fp2 == 0){
printf("close successful!\n");
}else if(fp2 == -1){
printf("Erreo:%s,errno:%d\n",strerror(errno),errno);
}
return 0;
}
*注意:这里的source和dest为具体的文件位置,写绝对路径。