Copy data from fstream to stringstream with no buffer?

Brad picture Brad · Oct 31, 2010 · Viewed 41.8k times · Source

Is there anyway I can transfer data from an fstream (a file) to a stringstream (a stream in the memory)?

Currently, I'm using a buffer, but this requires double the memory, because you need to copy the data to a buffer, then copy the buffer to the stringstream, and until you delete the buffer, the data is duplicated in the memory.

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;`

Does anyone know how I can write a whole file to a stringstream without using an inbetween buffer?

Answer

pinkfloydx33 picture pinkfloydx33 · Oct 31, 2010
 ifstream f(fName);
 stringstream s;
 if (f) {
     s << f.rdbuf();    
     f.close();
 }