简体   繁体   中英

Write to file with temporary buffer using ofstream

How can I write a series of numbers (in binary) preceded by its length, without knowing the length beforehand?

Can I write the number series to a temporary buffer (eg buf.write() ), determine the buffer length, and copy the buffer to an ofstream afterwards (eg ofs << buf )?

Since you are writing in binary mode to the file, reserve a location for the quantity.

For example, let's have an 32-bit value for the quantity. We could write that at the beginning of the file:

uint32_t number_size = 0U;

// Open output file for read & write.
// Reserve space for the quantity by writing dummy value.
output_file.write((char *)&number_size, sizeof(number_size));

// Perform calculations & writing to file, incrementing "number_size"  

// Write the number size to the top of the file:
output_file.seekp(0, SEEK_BEG);
output_file.write((char *)&number_size, sizeof(number_size));

You can place quantity variable anywhere, just remember its file position. When finished, seek to that position and write it in.

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