-1

I'm trying to refactor some code/libraries by trying to embed some resource files as binary objects using the objcopy tool. The files are .txt and .xml.

The original library contains some file read/write code, based on fopen, which I replaced by fmemopen() in order to load the files from memory instead of getting them from the disk.

My issue is that, the library also contains some std::ifstream objects that are used to read some other files from disk, and my question is how can I read those too from the memory?

I.e. I need either to assign a FILE* to an ifstream somehow, or if there is an equivalent of fmemopen()that is used for ifstreams.

std::ifstream input(pathToFilters);

NB. Please note that I'm trying to get an ifstream FROM a FILE and not the inverse (which has been already answered)

Thanks!

noureddine-as
  • 453
  • 4
  • 12
  • I used the following solution finally. [https://stackoverflow.com/questions/13059091/creating-an-input-stream-from-constant-memory](https://stackoverflow.com/questions/13059091/creating-an-input-stream-from-constant-memory) – noureddine-as May 22 '19 at 00:41

1 Answers1

1

Rather than open a FILE *, then try to create a stream from that, it's almost certainly going to be easier to create an istream that reads directly from memory.

An istringstream reads from a memory buffer, so that part is pretty easy.

So, you can create an istringstream object, passing it the data you want to read from, and then pass the istringstream to the code that expects to read from a stream. Normally, most code that deals with a stream should accept a reference to an istream or an ostream, in which case it'll accept a stringstream just as well as an fstream.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I searched about `istringstream`, and found out that to construct an object you need to give it a string, does this mean that I have to read all the files mapped to memory to a string then pass it as an argument to construct the `istringstream` ? Not sure if my understanding is correct. This solution would very inefficient I guess. I would like to have something that would read directly from the memory. – noureddine-as May 21 '19 at 09:16