writing struct to file in C

Hi,
I'm writing a structure to a file in C
here is the structure.
1
2
3
4
5
6
7
8
9
10
#define HD_MAGICNUMBER 0x4844415441
#define HD_VERSION 1

typedef unsigned long long key_num;
typedef struct hd_fileheader
{
    unsigned long long magic;
    unsigned short hdata_version;
    key_num next_key_num;
} hd_fileheader;


Here is the code used to write to the file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char hd_makefile(char* fname)
{
    FILE* desc = fopen(fname, "w+b");
    if (desc == NULL) {
        perror("hd_makefile: error while creating the file.\n");
        return -1;
    }
    hd_fileheader head = { HD_MAGICNUMBER, HD_VERSION, 1 };
    // Write the header to file.
    if (fwrite(&head, sizeof(hd_fileheader), 1, desc) != 1) {
        perror("hd_makefile: error while writing the header.\n");
        return -1;
    }
    fflush(desc);
    return 0;
}


The problem is that the output file (viewed with GHex2 is 20 bytes long althrough i'm using (8 * 2 + 2) bytes = 18 bytes.
Here is the hex view:
41 54 41 44 48 00 00 00 01 00 6C B7 01 00 00 00 00 00 00 00

As you can see the bytes of the MAGICNUMBER are inverted. I also cannot understand where does the 6C B7 comes from...
Thank you.
Hi

to pack your structure into 18 bytes you will need to use the pragma pack statements

1
2
3
4
5
6
7
8
9
10
11
12

#pragma pack(push, 1)

typedef struct hd_fileheader
{
    unsigned long long magic;
    unsigned short hdata_version;
    key_num next_key_num;
}

#pragma pack(pop)


The value of magic is reversed because of the way the computer stores integers. etc.
look up
Little Endian
if you want to find out why.

Hope this has been helpful
Shredded
Topic archived. No new replies allowed.