Writing binary files in C ++

I have a device that sends me binary data like uint32_t. I want to save data in a binary file. Here is my code:

#include<iostream> #include<fstream> #include <cstdlib> using namespace std; int main() { ofstream myFile ("data2.bin", ios::out | ios::binary); bool buffer[32]; for (int k = 0; k<100; k++) { for (int i = 0; i<32;i++) { buffer[i] = (bool)rand()%2; } myFile.write ((char*)&buffer, 32); } myFile.close(); } 

It works, but the file size is 3.2 kB, not 0.4 kB. Moreover, when I try to read data from a file (data created by my device), I get a strange outcome, and not in the format described in the manual. Of course, there is more data than I expect.

What am I doing wrong?

+5
source share
1 answer

A bool takes one byte. Check the sizeof(bool) and you will find it equal to 1. So the array is 32 bytes long and you write it 100 times, so 3.2kB.

If you want to save a bit array, you need to use something other than a bool array. You have several options:

  • Use an array of bytes, integers, or something the size of which you know, and explicitly include the bits you want. Then save the array.

     #include <iostream> #include <fstream> #include <cstdlib> #include <cstdint> using namespace std; int main() { ofstream myFile ("data2.bin", ios::out | ios::binary); uint32_t buffer; for (int k = 0; k<100; k++) { buffer = 0; for (int i = 0; i<32; i++) { buffer <<= 1; buffer |= (bool)(rand()%2); } myFile.write((char*) &buffer, sizeof(buffer)); } myFile.close(); return 0; } 

    In fact, if you already have an uint32_t array, then you do not need a loop, and you can just save the array directly. Use the exact line myFile.write above, where buffer is your uint32_t array.

  • Use vector<bool> or preferably a bitset . Both are optimized and use one bit for each element.

     #include <iostream> #include <fstream> #include <cstdlib> #include <bitset> using namespace std; int main() { ofstream myFile ("data2.bin", ios::out | ios::binary); bitset<32> buffer; for (int k = 0; k<100; k++) { for (int i = 0; i<32; i++) { buffer[i] = (bool)(rand()%2); } myFile.write((char*) &buffer, 32/8); } myFile.close(); return 0; } 

Of course, in both cases, you output bytes to your file. In the second case, the number of bits must be a multiple of 8.

+9
source

All Articles