我在这个 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;
}
有什么办法吗?
最佳答案
I cannot figure out how to iterate over the binary object with the same way i'm using ifstream when I open it directly
好吧,如果您想像读取二进制文件一样使用它,为什么还要使用其他东西呢?
也许你想做这样的事情:
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 托管内存段管理器)
关于c++ - 如何像二进制文件一样读取 boost mapped_region 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27506697/