Necesito leer un archivo completo en la memoria y colocarlo en C++ std::string
.Lea todo el archivo ASCII en C++ std :: string
Si tuviera que leerlo en un char[]
, la respuesta sería muy simple:
std::ifstream t;
int length;
t.open("file.txt"); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
t.close(); // close file handle
// ... Do stuff with buffer here ...
Ahora, yo quiero hacer exactamente lo mismo, pero usando un std::string
en lugar de un char[]
. Quiero evitar bucles, es decir, que no quiero:
std::ifstream t;
t.open("file.txt");
std::string buffer;
std::string line;
while(t){
std::getline(t, line);
// ... Append line to buffer and go on
}
t.close()
¿Alguna idea?
Siempre habrá un bucle implicado, pero puede estar implícito como parte de la biblioteca estándar. Es eso aceptable? ¿Por qué estás tratando de evitar los bucles? –
Creo que el afiche sabía que leer bytes implicaba bucles. Solo quería un equivalente fácil, estilo perl * gulp *. Eso implicó escribir un código pequeño. – unixman83
Este código tiene errores, en el caso de que std :: string no use un búfer continuo para sus datos de cadena (lo que está permitido): http://stackoverflow.com/a/1043318/1602642 –