【问题标题】:How read a boost mapped_region object like a binary file?如何像二进制文件一样读取 boost mapped_region 对象?
【发布时间】:2014-12-16 22:52:19
【问题描述】:

我在 Tutorial 之后使用 boost 库将一个二进制文件映射到内存中,但现在我无法弄清楚如何以与直接打开它时使用 ifstream 相同的方式迭代二进制对象:

这是代码

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>

...

file_mapping m_file(SHMFILE.c_str(), read_write);
mapped_region region(m_file, read_write);

我想做这样的事情:

ifstream myfile (region.get_address(), std::ios::in);
struct stat filestatus;
sstemp = filename.str();
const char * c = sstemp.c_str();
stat(c, &filestatus);
size = filestatus.st_size;
int cant = 0;

while (cant < size)
{

    myfile.read((char *) user_id, 4);   
    cant += 4;
}

有什么办法吗?

【问题讨论】:

    标签: c++ boost binary


    【解决方案1】:

    我无法弄清楚如何使用直接打开时使用 ifstream 的相同方式迭代二进制对象

    好吧,如果你想像读取二进制文件一样使用它,你为什么要使用其他东西?

    也许你想做这样的事情:

    file_mapping m_file(SHMFILE.c_str(), read_write);
    mapped_region region(m_file, read_write);
    
    char const* it = region.data();
    char const* e = it + region.size();
    
    for (; (it+4) <= e; it += 4)
    {
         auto user_id = *reinterpret_cast<uint32_t const*>(it);
    }
    

    再说一次,对于共享内存,我通常会以托管方式使用它(例如,使用 Boost Interprocess 托管内存段管理器)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多