C语言:文件复制

文本文件复制:

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;
}
相关推荐
哥不想学算法7 小时前
【C++】字符串字面量拼接
开发语言·c++
不像程序员的程序媛7 小时前
系统cpu内存负载资源分析
运维·服务器·数据库
gugucoding8 小时前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
Brookty9 小时前
【JavaEE】线程安全(一).4:写块串行保安全、CAS
java·开发语言·java-ee·多线程·线程安全
Uncertainty!!9 小时前
Ubuntu 22.04 安装超好用中文输入法rime-ice(雾凇拼音)过程记录
linux·ubuntu·中文输入法
F20226974869 小时前
西门子 PLC 与 C# 通信
开发语言·c#
gugucoding10 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ShineWinsu10 小时前
对于Linux:网络基础的解析
linux·网络·面试·udp·笔试·ip·tcp
万联WANFLOW11 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php