Pregunta

¿Hay alguna forma de transferir datos de una fstream (un archivo) a un stringstream (una corriente en la memoria)?

Actualmente, estoy usando un tampón, pero esto requiere el doble de memoria, ya que es necesario copiar los datos en un buffer, y luego copiar el búfer en el stringstream, y hasta que borre la memoria intermedia, los datos se duplica en la memoria.

std::fstream fWrite(fName,std::ios::binary | std::ios::in | std::ios::out);  
    fWrite.seekg(0,std::ios::end); //Seek to the end  
    int fLen = fWrite.tellg(); //Get length of file  
    fWrite.seekg(0,std::ios::beg); //Seek back to beginning  
    char* fileBuffer = new char[fLen];  
    fWrite.read(fileBuffer,fLen);  
    Write(fileBuffer,fLen); //This writes the buffer to the stringstream  
    delete fileBuffer;`

¿Alguien sabe cómo puedo escribir un archivo completo a un stringstream sin utilizar una memoria intermedia entre medio?

¿Fue útil?

Solución

// need to include <algorithm> and <iterator>, and of course <fstream> and <sstream>
ifstream fin("input.txt");
ostringstream sout;
copy(istreambuf_iterator<char>(fin),
     istreambuf_iterator<char>(),
     ostreambuf_iterator<char>(sout));

Otros consejos

 ifstream f(fName);
 stringstream s;
 if (f) {
     s << f.rdbuf();    
     f.close();
 }

En la documentación de ostream, hay varias sobrecargas para operator<< . Uno de ellos toma un streambuf* y lee todos los contenidos de la streambuffer.

Aquí es un uso de muestra (compilado y probado):

#include <exception>
#include <iostream>
#include <fstream>
#include <sstream>

int main ( int, char ** )
try
{
        // Will hold file contents.
    std::stringstream contents;

        // Open the file for the shortest time possible.
    { std::ifstream file("/path/to/file", std::ios::binary);

            // Make sure we have something to read.
        if ( !file.is_open() ) {
            throw (std::exception("Could not open file."));
        }

            // Copy contents "as efficiently as possible".
        contents << file.rdbuf();
    }

        // Do something "useful" with the file contents.
    std::cout << contents.rdbuf();
}
catch ( const std::exception& error )
{
    std::cerr << error.what() << std::endl;
    return (EXIT_FAILURE);
}

La única manera mediante la biblioteca de C ++ estándar es utilizar un ostrstream en lugar de stringstream.

Puede construir un objeto ostrstream con su propio char buffer, y va a tomar posesión de la memoria intermedia de entonces (por lo que no se necesita más de copiado).

Nota sin embargo, que la cabecera strstream está obsoleta (aunque su parte todavía de C ++ 03, y lo más probable es que siempre estará disponible en la mayoría de las implementaciones de la biblioteca estándar), y le conseguirá en grandes problemas si se olvida null-terminar los datos suministrados a las ostrstream.This también se aplica a los operadores de flujo, por ejemplo:. ostrstreamobject << some_data << std::ends; (nullterminates std::ends los datos)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top