I have some code that uses ifstream
to read some data from a file and everything works.
Now I wish, without modifying some code, read this data from a memory, actually I have a char *
that contains the data...
How can I put my char *
data into a ifstream
without reading effectively the file?
Although use of
std::istringstream
(sometimes erronously referred to without the leadingi
; such a class does exist but is more expensive to construct, as it also sets up an output stream) is very popular, I think it is worth pointing out that this makes—at a minimum—one copy of the actual string (I'd suspect that most implementations create two copies even). Creating any copy can be avoided using a trivial stream buffer:For a small area of memory, the difference may not matter, although the saved allocation can be noticable there, too. For large chunks of memory, it makes a major difference.
If the code that uses the
ifstream&
could be changed slightly to use anistream&
then you could easily switch betweenifstream
andistringstream
(for reading data from memory):Callers:
The standard library offers an in-memory
istream
that is also writeable:std::stringstream
.You need to properly abstract your code so that it accepts a generic
istream
instead of anifstream
, construct astringstream
, populate it with your data and pass that to the function.For example:
In my project I use the write() and read() methods of iostream, since I write binary data to a stringstream. Sorry, the following code is not tested and has probably syntax errors (typing from office... ;-), but something like this allows you to write to memory, files and elsewhere (e. g. network sockets):
You may be searching for a stringstream. http://www.cplusplus.com/reference/sstream/stringstream/. I've only used that once before and it's been a long time, but basically you can stream from a location in memory.