Search code examples
c++rhapsody

writing 32 bit binary data to a file using ofstream in C++


I am trying to write nothing but uint32_t data to a .bin file. I start by opening up a file stream which I declare to be a binary one.

  `hartInStream.open (hartFileToWrite.c_str(), std::ifstream::binary);
   if(!hartOutStream.is_open())
        {
        printf("Something in outstream went wrong.\n");  
        }
   else 
        {
        printf("Yippy! it outstream worked!\n");  
        printf("---------Starting to read-------------\n");}`

Next, I take the data I am trying to write, in this case a uint32_t "data", print it out, and write it to the end of my file stream.

printf(" Reading %lu from HART at %d-%d-%d\n", data, (int)addr1, (int)addr2, (int)addr3 );

Lastly I append the data

hartOutStream<<data;

I know that I should be writing 0x00 0x00 0x01 0x00 (256) as the first 4 bytes but I am writing 32 35 36 which is the hex equivalent of ascii charters to 256. (using HxD file viewer)

I suspect the problem is in the << operator where it typecasts it to ascii. I've tried typecasting, the atoi() function but nothing seems to work. Does anyone know what is wrong with this?

Thanks


Solution

  • ofstream f;
    f.open("my.bin",std::ofstream::binary);
    uint32_t data=0x00000100;
    f.write((char*)&data,sizeof(data));