Reading Files in C++, Quick and Easy

It’s a simple thing that can get needlessly complicated, especially if, like me, you return to C++ after a while of not using it. And then you ask yourself: “I need to read from a file but how did I use to do that? And what’s the best way to do this any way?
Well, I don’t know about best but this is the quickest and easiest way I could find.

std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();

And now your buffer contains the entire contents of the file and you may do with it as you please, using it like any other stream. Yes, streams allow you to output as strings two. You may even use a wstringstream if you want it to be encoded wide.
My problem came when my boss told me to dump the streams. But more on that later. Maybe.


Posted in Programming by with comments disabled.