Search code examples
c++pointersbinaryfilestypecasting-operator

Type casting pointer when writing to binary file in C++


Today in CS 111 class my instructor ended with a 'brief' look at writing structures to binary files. I say brief because he just included it as a kind of aside, saying it would not be on the final. Problem is, I don't fully understand what's going on in the program example and it is bothering me. Hopefully somebody will take the time to explain it to me. The code is as follows:

#include <iostream>
#include <fstream>
using namespace std;

struct PayStub
{
    int id_num;
    bool overtime;
    float hourly_rate;
};

int main()
{
    PayStub info = {1234, false, 15.45};

    ofstream data_store;

    data_store.open("test.cs111", ios::binary);

    char *raw_data = (char*)&info;
    data_store.write(raw_data, sizeof(PayStub));

    data_store.close();

    return 0;

}

I don't understand what is going on specifically in the statement char *raw_data = (char*)&info; and why it is necessary. I understand a pointer to a char is being declared and initialized, but what exactly is it being initialized to, and how is that being used in the next line? I hope this isn't a stupid question. Thanks in advance for your help.


Solution

  • char *raw_data = (char*)&info; after this line, raw_data will point to the address of the first byte of info.

    With data_store.write(raw_data, sizeof(PayStub)); we ask data_store to write to the file the contents in memory that start at raw_data and end at raw_data + sizeof(PayStub)).

    In essence we find the start address and length of PayStub and write it to disk.

    It is not a stupid question. Once you read up on pointers, everything will make sense.