c++ boost写入内存映射文件

标签 c++ boost memory-mapped-files

我正在寻找使用 C++ 和 boost 库快速编写文件的方法。我想使用内存映射文件。但几乎所有的例子都是关于阅读的。
工作很简单。有一个字符串数组。数组元素约200万。

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 确实使用映射文件,但您最好使用 IOstreams 进行这种原始访问。

参见 http://www.boost.org/doc/libs/1_50_0/libs/iostreams/doc/classes/mapped_file.html

Live On Coliru

#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"));
}

关于c++ boost写入内存映射文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33051067/

相关文章:

c++ - 在 32 位 Xp 计算机上构建 64 位 Qt

c++ - 使用 ptr 容器而不是普通容器给出 _Block_Type_Is_Valid

c++ - 返回需要由智能指针持有的 'pointer'

c++ - 内存分配 - Arduino

c++ - Qt如何创 build 置/配置窗口

c++ - 了解 std::copy

c++ - 对`class::class() 错误的 undefined reference

c++ - Boost regex_replace 异常 : "...This exception is thrown to prevent "eternal"matches. .."偶尔抛出

c - mmap访问文件内容并执行算术运算

java - 如果在执行 FileChannel.map() 时 MappedByteBuffer 的大小大于文件长度,会发生什么