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

来源:互联网 发布:博客网站源码 编辑:程序博客网 时间:2024/06/05 02:43

使用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;}
测试结果如下:

0 0