c++ use ifstream from memory

ghiboz picture ghiboz · Nov 27, 2012 · Viewed 9.2k times · Source

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?

Answer

Dietmar Kühl picture Dietmar Kühl · Nov 27, 2012

Although use of std::istringstream (sometimes erronously referred to without the leading i; 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:

struct membuf: std::streambuf {
    membuf(char* base, std::ptrdiff_t n) {
        this->setg(base, base, base + n);
    }
};
membuf sbuf(base, n);
std::istream in(&sbuf);

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.