How to read file content into istringstream?

std::ifstream has a method rdbuf(), that returns a pointer to a filebuf. You can then “push” this filebuf into your stringstream:

#include <fstream>
#include <sstream>

int main()
    std::ifstream file( "myFile" );

    if ( file )
        std::stringstream buffer;

        buffer << file.rdbuf();


        // operations on the buffer...

EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the stringstream‘s operator<< will read the filebuf character by character. You might want to check his answer, where he uses the ifstream‘s read method as you used to do, and then set the stringstream buffer to point to the previously allocated memory.

Leave a Comment