#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(){
char c;
int state1;
int state2;
char filename1[100] = {0};
char filename2[100] = {0};
char pathname1[100] = {0};
char pathname2[100] = {0};
int len,sourceLen,destLen;
char buf[BUF_SIZE];
char source[LEN],dest[LEN];
//open
puts("please input the source file:\n");
scanf("%s",filename1);
sprintf(pathname1,"/home/ben/c.d/%s",filename1);
puts("please input the destination file:\n");
scanf("%s",filename2);
sprintf(pathname2,"/home/ben/c.d/%s",filename2);
FILE *fp1;
FILE *fp2;
fp1 = fopen(pathname1,"r");
if(fp1 == NULL){
printf("fail to open file!\n");
exit(1);
}
fp2 = fopen(pathname2,"w+");
if(fp2 == NULL){
printf("fail to open file!\n");
exit(1);
}
//fgetc fputc
/*sourceLen = fseek(fp1,0,SEEK_END); //获取fp1文件的所有内容
rewind(fp1);//fseek(fp1,0,SEEK,SET) //读写位置移到开头
while(!feof(fp1)){
c = fgetc(fp1);
if(feof(fp1)){ //避免多一次的循环导致乱码,不懂可以参考feof用法
break;
}
fputc(c,fp2);
}
destLen = fseek(fp2,0,SEEK_END); //写到fp2的所有内容
if(sourceLen == destLen){
printf("copy successful!\n");
}else{
printf("source len:%d,dest len:%d",sourceLen,destLen);
}*/
//fgets fputs
/* sourceLen = fseek(fp1,0,SEEK_END);
rewind(fp1);//fseek(fp1,0,SEEK,SET)
while(!feof(fp1)){ //fgets到文件末尾就会停下,记录读到的内容buf,直接写进fp2,不需要判断是否会读超过文件末尾的内容,下面的fread和fwrite就不是如此
if(fgets(buf,sizeof(buf),fp1) == NULL){ //文件读到的内容==NULL 则已经是尝试读文件末尾的内容
break;
}
fputs(buf,fp2);
}
destLen = fseek(fp2,0,SEEK_END);
if(sourceLen == destLen){
printf("copy successful!\n");
}else{
printf("source len:%d,dest len:%d",sourceLen,destLen);
}*/
//fread,fwrite
sourceLen = fseek(fp1,0,SEEK_END);
rewind(fp1);//fseek(fp1,0,SEEK,SET)
while(len != 0){ //这里判断读文件末尾之后的内容就结束循环
len = fread(buf,1,sizeof(buf),fp1);
if(len < BUF_SIZE){ //读到文件末尾之后,实际读到的(len)小于我们要求去读的内容sizeof(buf),则我们写到文件的内容为实际得到的内容len,否则就写入我们要求的大小
fwrite(buf,1,len,fp2);
}else{
fwrite(buf,1,sizeof(buf),fp2);
}
}
destLen = fseek(fp2,0,SEEK_END);
if(sourceLen == destLen){
printf("copy successful!\n");
}else{
printf("source len:%d,dest len:%d",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;
}
文件操作之函数调用的文件内容拷贝(文件流)
最新推荐文章于 2020-08-05 11:41:52 发布