简体   繁体   中英

Writing binary data to a file

I want to temporarily cache binary data before I can write it to a file. This was my idea.

Since I have to insert a header before this data that indicates how much data will follow after the header, I needed a way to keep this data cached before it is written to ofstream file . I decided to create ostream buffer(); wherein I could dump all this data without writing it to the file.

After the header was written, I'd just do file << buffer to dump the data.

I'm still struggling with compiler errors such as this one:

error: no matching function for call to ‘TGA2Converter::writePixel(std::ostream (&)(), uint32_t&)’
note: candidate is: void TGA2Converter::writePixel(std::ostream&, uint32_t)

Why am I getting this message? And, perhaps more importantly, am I approaching the problem in the most effective and convenient way?


Edit: people have been asking for code. I tried to narrow it down to this...

// This is a file. I do not want to write the binary
// data to the file before I can write the header.
ofstream file("test.txt", ios::binary);

// This is binary data. Each entry represents a byte.
// I want to write it to a temporary cache. In my
// real code, this data has to be gathered before
// I can write the header because its contents depend
// on the nature of the data.
stringstream cache;
vector<uint32_t> arbitraryBinData;
arbitraryBinData.resize(3);
arbitraryBinData[0] = 0x00;
arbitraryBinData[1] = 0xef;
arbitraryBinData[2] = 0x08;

// Write it to temporary cache
for (unsigned i = 0; i < arbitraryBinData.size(); ++i)
    cache << arbitraryBinData[i];

// Write header
uint32_t header = 0x80;     // Calculation based on the data!
file << header;

// Write data from cache
file << cache;

I fully expected this binary data to be written to the file:

0000000: 8000 ef08

But I got this:

0000000: 3132 3830 7837 6666 6638 6434 3764 3139
0000010: 38

Why am I not getting the expected result?

ostream buffer(); is declaring a function called buffer taking no arguments and returning an ostream . Also ostream is a base class, you should be using strstream instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM