您的位置:首页 > 编程语言 > C语言/C++

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

2014-07-24 22:09 483 查看
使用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;
}
测试结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: