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];
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"
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With