10 Sept 2018

C++ I/O Tips: Saving Huge Text File using Boost Library

收藏到CSDN网摘
以前这篇文章写过利用Boost的内存映射来读取超大文件,但是读取的目的最终还是要写入结果文件.网络上使用Boost来读取文件的例子不少,但是写文件的例子则寥寥无几.记录一下,以备将来使用.


Boost在使用内存映射写文件时,一般是按照二进制来写.但是如果需要写入文本文件,则需要自己计算好大小(针对格式化好的文本比较好办).针对Node类,重载了operator <<(注意第二个参数必须是const Node&类型,如果少了const,编译会报错).然后,设置好映射参数,直接创建内存映射文件,使用上std::copy来复制内容到输出流就行.示例如下:
#include <iostream>
#include <vector>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>

namespace bio = boost::iostreams;
using namespace std;

int main()
{
vector<Node> strArray(20000000);
bio::mapped_file_params params;
params.path = "text.txt";
// 63 character per node, plus '\n' = 64 per node
params.new_file_size = 20000000*64;
params.flags = bio::mapped_file::mapmode::readwrite;

tic();
bio::stream<bio::mapped_file_sink> out(params);
// ostream_iterator requires Node class overload operator <<
copy(strArray.begin(), strArray.end(), ostream_iterator<Node>(out, "\n"));
toc("test boost writing");
return 0;
}

实验结果:
写入两千万个点大概用时47秒,机器: i7-2600,16G win10-64bit.
原来循环写三百六十多万个点大概就像也要40秒,提速还是很可观的.

1 comment :