How to copy binary data from one stream to another?

11,891

Use the streambuf members, that's what they are for:

fout << ss.rdbuf();
Share:
11,891
Fabi1816
Author by

Fabi1816

Updated on July 18, 2022

Comments

  • Fabi1816
    Fabi1816 almost 2 years

    Currently i have a program that loads binary data into a stringstream and then pases the data to a fstream like so:

    stringstream ss(stringstream::binary | stringstream::in | stringstream::out);
    ss.write(data, 512);  // Loads data into stream
    
    // Uses a memory block to pass the data between the streams
    char* memBlock = new char[512];
    ss.read(memBlock, 512);
    
    ofstream fout("someFile.bin", ios::binary);
    fout.write(memBlock, 512);  // Writes the data to a file
    fout.close();
    
    delete[] memBlock;
    

    My question is: is there a better way to pass the binary data between the streams?

  • Fabi1816
    Fabi1816 over 13 years
    Isn´t "operator<<" for formated input? i´m working with binary data.
  • Alexandre C.
    Alexandre C. over 13 years
    @Fabi1816: There is an overload for streambuf which does binary output. This overload is here to do exactly what you request here.
  • Stephen
    Stephen about 10 years
    This is functionally correct. I've found copying data with C++ streams to be 2-3 times slower than using the C style methods posted above. Much to my annoyance.
  • StanE
    StanE almost 8 years
    Also, the entire stream is copied. Sometimes one needs to copy data from a certain offset and/or a certain amount of bytes only.