我试图了解 Boost 内存映射文件是如何工作的。以下代码有效,它完成了它应该做的事情,但问题是它生成的文件存储在磁盘上(在可执行文件的同一目录中)而不是内存。也许在某处设置了一个标志,但我找不到它......
提前感谢您提供任何信息!
#include <iostream>
#include <string>
#include <cstring>
#include <boost/iostreams/device/mapped_file.hpp>
using std::cout;
using std::endl;
int main(int argc, char** argv) {
const int blockSize = 64;
bool writer = false;
if(argc > 1) {
if(!strcmp(argv[1], "w"))
writer = true;
}
boost::iostreams::mapped_file_params params;
params.path = "map.dat";
// params.length = 1024; // default: all the file
params.new_file_size = blockSize;
if(writer) {
cout << "Writer" << endl;
params.mode = std::ios_base::out;
}
else {
cout << "Reader" << endl;
params.mode = std::ios_base::in;
}
boost::iostreams::mapped_file mf;
mf.open(params);
if(writer)
{
char *block = mf.data();
strcpy(block, "Test data block...\0");
cout << "Written: " << block << endl;
}
else
{
cout << "Reading: " << mf.const_data() << endl;
}
mf.close();
return 0;
}
/*
Compiler options: -Wall -I$(PATH_BOOST_INCLUDE) -ggdb
Linker options: -L$(PATH_BOOST_LIBS) -lboost_iostreams-mt -lboost_system-mt -lboost_filesystem-mt -DBOOST_FILESYSTEM_NO_DEPRECATED
*/
使用的编译器:gcc 4.2.1
Boost 1.41.0
操作系统:MacOS X 10.6.2