Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a one-liner to read in a file to a string in C++?

I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.

Equivalent of this if you know Cocoa:

NSString *string = [NSString stringWithContentsOfFile:file];
like image 983
robottobor Avatar asked Sep 25 '08 22:09

robottobor


2 Answers

We can do it but it's a long line :

#include<fstream>
#include<iostream>
#include<iterator>
#include<string>

using namespace std;

int main()
{
    // The one-liner
    string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>());

    // Check result
    cout << fileContents;
}

Edited : use "istreambuf_iterator" instead of "istream_iterator"

like image 83
Rexxar Avatar answered Oct 09 '22 20:10

Rexxar


Its almost possible with an istream_iterator (3 lines!)

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    ifstream file("filename.txt");
    string fileContents;

    copy(istreambuf_iterator<char>(file),
              istreambuf_iterator<char>(),
              back_inserter(fileContents));
}

Edited - got rid of intermediate string stream, now copies straight into the string, and now using istreambuf_iterator, which ignores whitespace (thanks Martin York for your comment).

like image 33
Doug T. Avatar answered Oct 09 '22 22:10

Doug T.