Six, C language realizes the copy of text files and binary files
1. Code implementation
#include<stdio.h>
#include<assert.h>
//文本文件拷贝
void TxtFileCopy(FILE* des, FILE* arc)
{
assert(arc != NULL);//添加断言==if(arc==NULL) printf("源文件不存在,无法读取");
while (1)
{
char ch = fgetc(arc);
if (ch == EOF) break;
fputc(ch, des);
}
printf("拷贝成功!\n");
fclose(arc);
fclose(des);
}
//二进制文件拷贝
void BinaryFileCopy(FILE* des, FILE* arc)
{
assert(arc != NULL);
char buffer[10];
int tmp=0;
//注意:fread()的返回值
while ((tmp = fread(buffer, sizeof(char), 10, arc))!=0)
{
fwrite(buffer, sizeof(char), 10, des);
}
printf("拷贝成功\n");
fclose(arc);
fclose(des);
}
int main()
{
/*FILE* fp = fopen("D:\\text.txt", "r");
FILE* fw = fopen("D:\\text1.txt", "w");
TxtFileCopy(fw, fp);//文本文件拷贝*/
FILE* fp = fopen("D:\\jay.mp3", "rb");
FILE* fw = fopen("D:\\1.mp3", "wb");
BinaryFileCopy(fw, fp);//二进制文件拷贝
return 0;
}
2. Test results
- Text file
- Binary file (a song .mp3 file by Jaylen is used here)
3. Summary
- Pay more attention to the difference between text files and binary files
- Pay attention to the return value when using the fread() function