Sign in to follow this  

Stupid STL Question

This topic is 3869 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to read an entire file into a string using ifstream but the ifstream.read seems to need a char*. How do I read the data into a string without using a char* and initializing the string with it? Or is there another STL class that works better?

Share this post


Link to post
Share on other sites
Quote:
Original post by linternet
I'm trying to read an entire file into a string using ifstream but the ifstream.read seems to need a char*.


#include <algorithm>
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

using namespace std;

const string filename("sb.cpp");

int main()
{
ifstream istr(filename.c_str());
if (!istr)
{
cerr << "error " << errno << " opening " << filename << ": "
<< strerror(errno) << "\n";
exit(1);
}

string image = string(istreambuf_iterator<char>(istr),
istreambuf_iterator<char>());

cout << "image length is " << image.length() << "\n";
cout << "-- begin image dump --\n";
cout << image << "\n";
cout << "-- end image dump --\n";
}


Share this post


Link to post
Share on other sites

This topic is 3869 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this