文本文件复制:
cpp
#include<stdio.h>
int main()
{
FILE* pFile1 = NULL;
FILE* pFile2 = NULL;
fopen_s(&pFile1,"D:\\11111.txt","r");
fopen_s(&pFile2,"D:\\222.txt", "w");
char c;
while((c=fgetc(pFile1))!=EOF)
{
fputc(c,pFile2);
}
fclose(pFile1);
fclose(pFile2);
return 0;
}
二进制文件复制:
cpp
#include<stdio.h>
int main()
{
FILE* pfile1 = NULL;
FILE* pfile2 = NULL;
fopen_s(&pfile1, "C:\\Users\\ljw\\Desktop\\WIN_20231103_17_32_35_Pro.jpg", "rb");//一张图片
fopen_s(&pfile2, "d:\\abc.jpg", "wb");
char buf[1024];
while (fread(buf, 1, 1024, pfile1) > 0)//返回值>0代表读取成功
{
fwrite(buf, 1, 1024, pfile2);
}
fclose(pfile1);
fclose(pfile2);
return 0;
}
但在二进制文件复制这里我们会发现一个问题:那就是复制过来文件大小的大于原文件的大小。
cpp
#include<stdio.h>
int main()
{
FILE* pfile1 = NULL;
FILE* pfile2 = NULL;
fopen_s(&pfile1, "C:\\Users\\ljw\\Desktop\\WIN_20231103_17_32_35_Pro.jpg", "rb");
fopen_s(&pfile2, "d:\\abc.jpg", "wb");
char buf[1024];
size_t nread,nwrite;
while ((nread=fread(buf, 1, 1024, pfile1)) > 0)
{
nwrite=fwrite(buf, 1, 1024, pfile2);
printf("%d %d\n", nread, nwrite);
//发现最后一次读取不足1024,但写入仍为1024,因此造成
//要解决此问题只需将nwrite=fwrite(buf, 1, 1024, pfile2);中的1024改为nread即可
}
fclose(pfile1);
fclose(pfile2);
return 0;
}