[英]c++ boost write memory mapped file
我正在寻找使用C ++和boost库快速编写文件。 我想使用内存映射文件。 但几乎所有的例子都是关于阅读。
工作很简单。 有一个字符串数组。 数组元素大约有2百万。
ofstream outFile("text.txt");
for (int i = 0; i < 2000000; ++i) {
outFile << strArray[i] << "\n";
}
outFile.close();
我怎么能用内存映射文件呢? 我在哪里可以找到使用内存映射文件的文件?
谢谢你的关心。
您可以使用Boost Iostreams mapped_file{_sink,_source}
。
尽管Boost Interprocess确实使用了映射文件,但您最好使用IOstream进行这种原始访问。
请参阅http://www.boost.org/doc/libs/1_50_0/libs/iostreams/doc/classes/mapped_file.html
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
#include <vector>
namespace bio = boost::iostreams;
int main() {
using namespace std;
vector<string> strArray(2000000);
bio::mapped_file_params params;
params.path = "text.txt";
params.new_file_size = 30ul << 30;
params.flags = bio::mapped_file::mapmode::readwrite;
bio::stream<bio::mapped_file_sink> out(params);
copy(strArray.begin(), strArray.end(), ostream_iterator<string>(out, "\n"));
}
有一个专门用于此的增强库。 它被称为“增强进程间”。
文档(带示例)在这里:
http://www.boost.org/doc/libs/1_59_0/doc/html/interprocess.html
我知道没有可移植的方式来做内存映射文件(虽然可能有一些东西,提升通常会......)。 你在用Linux吗? 然后有很好的机制来编写具有内存映射文件的高性能内容,例如mmap(2)。 这些机制也部分可移植到其他主要的Unix操作系统:es。 (是的,Linux是Unix)对于某些应用程序,使用线程(当然共享虚拟内存空间)是另一种选择。 然后你没有可移植性问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.