Search code examples
c++ifstreammemcpy

c++ use ifstream from memory


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?


Solution

  • If the code that uses the ifstream& could be changed slightly to use an istream& then you could easily switch between ifstream and istringstream (for reading data from memory):

    void read_data(std::istream& in)
    {
    }
    

    Callers:

    std::istringstream in_stream(std::string("hello"));
    read_data(in_stream);
    
    std::ifstream in_file("file.txt");
    read_data(in_file);