jeudi 26 mars 2015

avoid copy from reading file to string

Trying to figure out if there is a way to avoid this copy operation when reading a file into a string in any of the following ways.




Copy made from calling t.str().



std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
return t.str(); // Copy




No copy operation here, but buffer does not contain the entire file after read.



std::ifstream t("file.txt");
t.seekg(0, std::ios::end);
size_t size = t.tellg();
std::string buffer(size, ' ');
t.seekg(0);
t.read(&buffer[0], size);


This way is also pretty ugly with default-instantiating the string with size number of spaces.




No copy, but contents are in char * and string(block) would perform a copy.



std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;


Can't find a possible way to create string from char * without making a copy.


Aucun commentaire:

Enregistrer un commentaire