cmoremore
cmoremore

Reputation: 13

How read a boost mapped_region object like a binary file?

I mapped a binary file into memory following this Tutorial using boost library but now I cannot figure out how to iterate over the binary object with the same way i'm using ifstream when I open it directly:

This is the code

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

I want to do something like that:

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

Is there some way to do it?

Upvotes: 1

Views: 570

Answers (1)

sehe
sehe

Reputation: 393114

I cannot figure out how to iterate over the binary object with the same way i'm using ifstream when I open it directly

Well, if you want to use it exactly as when just readin a binary file, why are you using something else?

Maybe you want to do something like this:

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

Then again, with shared memory, I'd usually use it in a managed fashion (e.g. using Boost Interprocess managed memory segment managers)

Upvotes: 2

Related Questions