简体   繁体   English

写入和读取映射文件C ++

[英]Writing and Reading to/from a Mapped File C++

I have this struct: 我有这个结构:

struct DataItem
{
  std::string tag;        
  vector<unsigned char> data_block;
  time_t input_time;     
  int version_mark; 
};

What i am trying to do is to create a 10MB file with boost (1.47.0 version & Windows platform) map that file to memory and write some data of this struct type in a method. 我想做的是创建一个带有Boost(1.47.0版和Windows平台)的10MB文件,将该文件映射到内存,并在方法中写入此struct类型的一些数据。 It is this one: (I did not fill all the atrributes of the struct since I am just trying the functionality) 就是这个:(因为我只是在尝试功能,所以我没有填写结构的所有特性)

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);

    }

}

And from another function i am trying to read that data from the file like this: (I just pop_back the last data to see at least if there is data on the file) 从另一个函数中,我试图像这样从文件中读取该数据:(我只是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;
}

The file is created to my hard drive physically but the problem is myVector2 is empty every time (i can observe it from watch pane), so i can not test even i succeed to write data to the file or not. 该文件是物理创建到我的硬盘上的,但是问题是myVector2每次都是空的(我可以从观察窗格中观察到它),因此即使我成功地将数据写入或不写入文件,我也无法进行测试。 By the way also the compiler gaves an access violation error in the last line (cout line) 顺便说一句,编译器还在最后一行(cout行)给出了访问冲突错误。

Can anyone tell me please am i misunderstanding the managed_map_file concept, or what is wrong with this code? 谁能告诉我我是否误解了managed_map_file概念,或者此代码有什么问题?

You are creating a vector named "MyVector" in the putData function but you are searching a vector named "MyVector2" in the getData function. 您正在putData函数中创建一个名为“ MyVector”的向量,但是正在getData函数中搜索一个名为“ MyVector2”的向量。 The names have to be identical. 名称必须相同。 It's like an identifier. 就像一个标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM