我正在寻找使用 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
#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/