读一个文本文件,并用二进制方式生成相应的新文件,并比较两个文件的大小要求两个文件名从键盘输入

该程序演示了如何使用C++从用户输入读取原始文件名和新文件名,然后以二进制模式打开并读取原始文件,并生成新的二进制文件。通过比较两个文件的字节数,确定哪个文件更大。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "iostream"
#include "string"
#include <iomanip>  
#include <fstream>  
#include <cstdlib> 
using namespace std;

int main()
{
	string oriFilename,newFilename;
	cout<<"输入原文件名:";
	cin>>oriFilename;
	cout<<"输入新文件名:";
	cin>>newFilename;

	fstream infile,outfile;
	infile.open(oriFilename,ios::in | ios::binary);
	outfile.open(newFilename,ios::out | ios::binary);

	if (!fin)
	{
		cout<<"open error!"<<endl;
	}
	else
	{
		int buffer[1024];
		int intCountOri = 0,intCountNew = 0;
		while(!fin.eof())  //判断是否读到文件尾
		{
			fin.read((char *)buffer,1024);  //二进制文件要用read
			intCountOri = fin.gcount();  //获取原文件的实际字节数
			fout.write((char *)buffer,intCountOri);  //生成相应的二进制文件,二进制写用write
		}

		fin.close();
		fout.close();

		fin.open(newFilename);
		char ch;
		while(fin.get(ch))
			intCountNew++;

		cout<<"原文件:"<<intCountOri<<endl;
		cout<<"新文件:"<<intCountNew<<endl;

		if (intCountOri > intCountNew)
		{
			cout<<"原文件大。";
		} 
		else
		{
			cout<<"新文件大。";
		}
		fin.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值