C语言版:
#include <bits/stdc++.h>
using namespace std;
int main(){
//文本文件复制
FILE* f1=fopen("input.txt","r");
FILE* f2=fopen("out.txt","w");
if(!f1||!f2) {
printf("-1\n");
return -1;
}
char buf[5];
while(fgets(buf,sizeof(buf),f1)!=NULL){
printf("%s\n",buf);
fputs(buf,f2);
}
fclose(f1);
fclose(f2);
//二进制文件复制
FILE* f1=fopen("input.txt","rb");
FILE* f2=fopen("out.txt","wb");
if(!f1||!f2){
printf("-1\n");
return -1;
}
char buf[1024];
int len=sizeof(buf);
while(!feof(f1)){
memset(buf,0,sizeof(buf));
if(fread(buf,sizeof(buf),1,f1)!=1){
char *p=&buf[len-1];
while((*p)==0){
p--;
len--;
}
}
fwrite(buf,len,1,f2);
}
fclose(f1);
fclose(f2);
return 0;
}
C++版:
#include <bits/stdc++.h>
using namespace std;
const int maxn=(1<<10);
int main(){
//二进制
ifstream fin("1.jpg",ios::binary); //acsii码 读为ios::in
ofstream fout("2.jpg",ios::binary); //………………… …………Ios::out
while(!fin.eof()){
char buf[maxn]="";
int len=sizeof(buf);
fin.read(buf,sizeof(buf));
if(fin.peek()==-1){
char *p=&buf[len-1];
while((*p)==0){
len--;
p--;
}
}
fout.write(buf,len);
}
fin.close();
fout.flush();
fout.close();
return 0;
}