C++ 实现复制任意文件并显示完成百分比

使用C++ 实现复制文件,   就要涉及到文件读写操作 主要涉及到C++中两个类:ifstream(输入文件流)ofstream(输出文件流),这里输入输出是相对于内存而言。

实现代码如下所示:(这里我们以读取avi视频为例)实现将C盘中3.avi复制到D盘3.avi

// Copy_file.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;
const int BUFF_SIZE=1024;

int _tmain(int argc, _TCHAR* argv[])
{
	ifstream input_file_stream; //定义输入文件流
	ofstream out_file_stream;//定义输出文件流
	double d_file_length,d_read_length=0;//d_file_length 文件总长 ,d_read_length 已经读取的文件长度
	int i_count=0;//记录读取次数
	int i_percent;

	input_file_stream.open("C:\\3.avi",std::ios::binary);// 以输入流打开文件
	out_file_stream.open("D:\\3.avi",std::ios::binary);// 以输出流打开文件
	if (!input_file_stream)
	{
		cout<<"input_file_stream 打开文件失败"<<endl;
		system("pause");
		return 1;
	}
	if (!out_file_stream)
	{
		cout<<"out_file_stream 打开文件失败"<<endl;
		system("pause");
		return 1;
	}
	input_file_stream.seekg(0, ios::end);//将文件指针移动至末尾
	d_file_length=input_file_stream.tellg();// 获取文件长度
	input_file_stream.seekg(0,ios::beg);//将文件指针移到至开始


	while(!input_file_stream.eof())
	{
		i_count++;
		char szBuf[BUFF_SIZE] = {0};  
		d_read_length+=BUFF_SIZE;
		input_file_stream.read(szBuf, sizeof(char) * BUFF_SIZE);  

		if (input_file_stream.bad())  
		{   
			cout<<"读取文件异常"<<endl;
			break;  
		}  
		if(i_count%10240==0)
		{
			i_percent=100*d_read_length/d_file_length;
			cout<<"has complete "<<i_percent<<"%"<<endl;
		}
		out_file_stream.write(szBuf, sizeof(char) * BUFF_SIZE);
	}

	input_file_stream.close();
	out_file_stream.close();

	if (i_percent!=100)
	{
		cout<<"has complete "<<100<<"%"<<endl;;
	}

	system("pause");
	return 0;
}


测试结果如下:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值