前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++ 文件分块

c++ 文件分块

作者头像
一灰灰blog
发布2018-02-06 11:57:45
1.5K0
发布2018-02-06 11:57:45
举报
文章被收录于专栏:小灰灰

对大文件进行分块处理,这里只是简单的顺序执行

可考虑实现并发分块,通过文件指针的位置及偏移来实现

代码语言:javascript
复制
#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 


#define KB_4 4096 
#define KB_8 8192 
#define KB_16 16384 
#define KB_32 32768 
#define KB_64 65536L 
#define KB_128  131072L 
#define KB_256 262144L 
#define KB_512 524288L 
#define MB_1 1048576L 
#define MB_2 2097152L 
#define MB_4 4194304L 


using namespace std; 


string int_to_str(int i) 
{ 
stringstream ss; 
ss << i ; 
return ss.str(); 
} 


bool write_file(char * block, int length, const string & filename) 
{ 
ofstream ofs(filename.c_str()); 
if(!ofs.is_open()) 
{ 
cout << "Failed to open the file!" << endl; 
return false; 
} 

ofs.write(block, length); 


ofs.close(); 
return true; 
} 


void test() 
{ 

const int size = MB_2; 
ifstream ifs("1GB"); 
if(!ifs.is_open()) 
{ 
cout << "Failed to open the file!" << endl; 
return ; 
} 


string block_id = ""; 
string head = "2MB/"; 

char block[size]; 

int i = 1; 
do 
{ 
block_id = head + int_to_str(i++); 
if(ifs.read(block, size) == 0) 
break; 

if(!write_file(block, size, block_id)) 
{ 
cout << "error!" << endl; 
break; 
} 
}while(!ifs.eof()); 
ifs.close(); 
cout << "over!" << endl; 
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
大数据
全栈大数据产品,面向海量数据场景,帮助您 “智理无数,心中有数”!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档