Home > Net >  How to read data from a binary file and write to a shared memory region?
How to read data from a binary file and write to a shared memory region?

Time:09-09

I have created a shared memory region using boost. My next step is to read data from a binary file and write it to the shared memory region. I am using the following code to do this:

#include <fstream>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>

using namespace std;
using namespace boost::interprocess;

int main(int argc, char **argv)
{
    ifstream file;
    file.open("sigData.bin", ios::binary | ios::in); // file is of 1mb

    shared_memory_object shm(open_or_create, "shared_memory", read_write);

    shm.truncate(1024 * 1024);

    mapped_region region(shm, read_write);

    unsigned char * mem = static_cast<unsigned char*> (region.get_address());

    file.read(mem, region.get_size());
}

The above code gives me an error on the file.read() function. The error is as follows:

error: invalid conversion from ‘unsigned char*’ to ‘std::basic_istream<char>::char_type* {aka char*}’ [-fpermissive]

How do I solve this issue?

CodePudding user response:

This can be solved by casting the pointer from unsigned char* to char*; this is one of the rare cases where just changing the type of a pointer is OK.

So, use

file.read(reinterpret_cast<char*>(mem), region.get_size());
  • Related