boost 文件映射

boost 的文件映射的使用非常简单
两个类就搞定了。file_mapping mapped_region
但当映射的region和文件大小一样时,当文件大于1g时 产生异常,
此时只能分段映射文件才能避免以上问题。
region的粒度由获得 std::size_t page_size = mapped_region::get_page_size();

2:向region中写入数据,读出数据
时应小心
如下面的实例中/**NOTIC*/部分
示例:

// testboostmapregion.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <cstddef>
#include <cstdlib>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost::interprocess;
     file_mapping::remove("e:\\output\\strucRegionfile.bin");

const std::size_t FileSize = 1000 * mapped_region::get_page_size();
{  //Create a file
std::filebuf fbuf;
fbuf.open("e:\\output\\strucRegionfile.bin", std::ios_base::in | std::ios_base::out 
| std::ios_base::trunc | std::ios_base::binary); 
//Set the size
fbuf.pubseekoff(FileSize-1, std::ios_base::beg);
fbuf.sputc(0);
}
//Remove file on exit
struct file_remove 
{
~file_remove (){  file_mapping::remove("e:\\output\\strucRegionfile.bin"); }
} destroy_on_exit;

struct item{
double d1;
int n1;
float f1;
} ;

//Create a file mapping
file_mapping m_file("e:\\output\\strucRegionfile.bin", read_write);


//Map the whole file with read-write permissions in this process
try{ 
mapped_region region(m_file, read_write);//,10,10000000);

//Get the address of the mapped region
void* addr       = region.get_address();/*notic*/
std::size_t size  = region.get_size();

//Write all the memory to 1
std::memset(addr, 0, size);

//int sizeitem = sizeof(item);

char* _items = (char*)addr;

item it;
it.d1 =9.8;
it.f1 =7.3;
it.n1 =3;

cout<<"in: d1: "<<it.d1<<" f1: "<<it.f1<<" n1:"<<it.n1<<endl;

//*((item*)(addr+size-sizeof(item)))
*((item*)(_items+size-sizeof(item))) =it;//ok/*notic*/
//memcpy(addr+size - sizeof(item),&it,sizeof(item));//ok/*notic*/

item  out = *((item*)(_items+size-sizeof(item)));//ok/*notic*/
//memcpy(&out,addr+size - sizeof(item),sizeof(item));//ok/*notic*/

cout<<"out: d1: "<<out.d1<<"f1: "<<out.f1<<" n1:"<<out.n1<<endl;
}
catch( boost::interprocess::interprocess_exception& ex  ){
cout << "\n mapped_region exception.what:" << ex.what() << endl;
}
//Launch child process
//std::string s(argv[0]); s += " child ";
// if(0 != std::system(s.c_str()))

m_file.remove("e:\\output\\file.bin");
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值