[英]Writing and Reading to/from a Mapped File C++
我有這個結構:
struct DataItem
{
std::string tag;
vector<unsigned char> data_block;
time_t input_time;
int version_mark;
};
我想做的是創建一個帶有Boost(1.47.0版和Windows平台)的10MB文件,將該文件映射到內存,並在方法中寫入此struct類型的一些數據。 就是這個:(因為我只是在嘗試功能,所以我沒有填寫結構的所有特性)
void putData()
{
managed_mapped_file mfile(create_only,"MyMappedFile", 10485760);
typedef allocator<int, managed_mapped_file::segment_manager> MnmapfileAllocator;
typedef vector<DataItem,MnmapfileAllocator> MyVector;
const MnmapfileAllocator alloc_inst (mfile.get_segment_manager());
MyVector *myvector = mfile.construct<MyVector>("MyVector")(alloc_inst);
time_t t = time(0);
struct tm* now = localtime(&t);
for (int j=0; j<10; j++)
{
DataItem data;
data.version_mark = j;
data.timestamp = now->tm_sec;
myvector->push_back(data);
}
}
從另一個函數中,我試圖像這樣從文件中讀取該數據:(我只是pop_back最后一個數據以查看至少文件上是否有數據)
void getData()
{
DataItem data;
managed_mapped_file mfile(open_only,"MyMappedFile");
typedef allocator<int, managed_mapped_file::segment_manager> MnmapfileAllocator;
typedef vector<DataItem,MnmapfileAllocator> MyVector2;
const MnmapfileAllocator alloc_inst (mfile.get_segment_manager());
MyVector2 *myvector2 = mfile.find<MyVector2>("MyVector2").first;
myvector2->pop_back();
std::cout << myvector2->back().version_mark << std::endl;
}
該文件是物理創建到我的硬盤上的,但是問題是myVector2每次都是空的(我可以從觀察窗格中觀察到它),因此即使我成功地將數據寫入或不寫入文件,我也無法進行測試。 順便說一句,編譯器還在最后一行(cout行)給出了訪問沖突錯誤。
誰能告訴我我是否誤解了managed_map_file概念,或者此代碼有什么問題?
您正在putData函數中創建一個名為“ MyVector”的向量,但是正在getData函數中搜索一個名為“ MyVector2”的向量。 名稱必須相同。 就像一個標識符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.