Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way of reading an ifstream into an string?

Tags:

c++

std

noob question! How can i read 'a whole ifstream' into a stdlib 'string'? The current way i'm using for all my projects right now wastes much time i think:

string code;
ifstream input("~/myfile");
char c1=input.get();
while (c1!=EOF)
{
    code+=c1;
    len++;
    c1=input.get();
}

BTW i prefer to do line and whitespace management myself.

like image 820
Hossein Avatar asked Oct 24 '25 05:10

Hossein


1 Answers

string load_file(const string& filename)
{
    ifstream infile(filename.c_str(), ios::binary);
    istreambuf_iterator<char> begin(infile), end;
    return string(begin, end);
}
like image 135
genpfault Avatar answered Oct 26 '25 19:10

genpfault