Sign in to follow this  
linternet

Stupid STL Question

Recommended Posts

linternet    344
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
ToohrVyk    1595
std::vector<char>, which is guaranteed to be contiguous. Resize it to an adapted size, and then pass the address of its first element to the reading function.

Share this post


Link to post
Share on other sites
Bregma    9199
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

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