I need to copy a file into a string. I need someway to preallocate memory for that string object and a way to directly read the file content into that string\'s memory?
This should be all you need:
ostringstream os;
ifstream file("name.txt");
os << file.rdbuf();
string s = os.str();
This reads characters from file and inserts them into the stringstream. Afterwards it gets the string created behind the scenes. Notice that i fell into the following trap: Using the extraction operator will skip initial whitespace. You have to use the insertion operator like above, or use the noskipws manipulator:
// Beware, skips initial whitespace!
file >> os.rdbuf();
// This does not skip it
file >> noskipws >> os.rdbuf();
These functions are described as reading the stream character by character though (not sure what optimizations are possible here, though), i haven't timed these to determine their speed.