0

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;
file.open("test.bin", std::ios::out | std::ios::binary);
for each(int i in vectorOfInts) {
    file << i;
}
file.close();
anonymous noob
  • 807
  • 1
  • 7
  • 10
  • Use [`file.write()`](http://en.cppreference.com/w/cpp/io/basic_ostream/write) then. – πάντα ῥεῖ Oct 20 '16 at 18:35
  • 1
    Possible duplicate of [Why use unsigned chars for writing to binary files? And why shouldn't stream operators be used to write to binary files?](http://stackoverflow.com/questions/7460206/why-use-unsigned-chars-for-writing-to-binary-files-and-why-shouldnt-stream-ope) – Jim Lewis Oct 20 '16 at 18:38
  • Why do you want to write "00 00 00 01"? – RyanP Oct 20 '16 at 18:39
  • so that when I read the file I just read 4 bytes at a time to get my desired integer – anonymous noob Oct 20 '16 at 18:46

1 Answers1

7

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));
pcarter
  • 1,516
  • 14
  • 21