something that should have been included in C++ by default
string file2str(string filename)
{
int length;
char * buffer;
ifstream is;
is.open (filename.c_str(), ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
is.close();
string retval(buffer,length); // null characters have no effect
return retval;
}
Nine times out of ten, reading the whole file into memory at once and then parsing it with a stringstream is over 5-10 times faster than doing the reading and parsing at the same time with an ifstream, because the ifstream ends up sending a lot of little read requests to the hard drive instead of one long sequential read, and the one long sequential read is going to be a lot faster on almost every machine.
Load Comments...
Discuss...
Enable JavaScript to submit a comment.