anonymous noob anonymous noob - 1 year ago 122
C++ Question

c++ how to write integers to a binary file that stay 4 bytes long

I want to write a bunch of integers to a file and then be able to read them later. My problem is that when I write the integers to a file, smaller integers end up using less than 4 bytes. So 1 for example is represented as 01 rather than 00 00 00 01. This means I'll have trouble reading the file because I don't know where one integer begins and ends. How do I make it so that the integer I write to the file is always 4 bytes long? My code is below:

std::fstream file;"test.bin", std::ios::out | std::ios::binary);
for each(int i in vectorOfInts) {
file << i;

Answer Source

You seem to be confused between text and binary files. The << operator is used for text files. It converts the value to text and writes that to the file. You need to use the write method to write an integer in native binary format to a file. The below would write out the 4 bytes to the file.

file.write( reinterpret_cast<const char *>(&i), sizeof(i));

You may also need to consider the endianness of data depending on what will be reading the data back.

You could also write the whole vector without a loop using:

file.write( reinterpret_cast<const char *>(&vectorOfInts[0]), vectorOfInts.size()*sizeof(int));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download