All,

I have a program that writes a binary config file for another piece 
of hardware.  One of the requirements of the file is that integer 
values are 32 bits.  Currently the file is created as expected when 
run on a 32 bit machine.  However, I need to make it portable, so 
that it could also be run on a machine that uses 64 bit ints, and 
I'm not sure how to do it.

Currently, the code is something like this:

struct Data
{
   int nInt1;
   int nInt2;
   char czString[32];
};

...

FILE* pFile = fopen("filename.bin", "wb");
Data data;
// do stuff

fwrite(&data, sizeof(data), 1, pFile);

...

Now, I know this is not portable because of int size (as well as 
possible packing issues) so I thought about changing it to something 
like this:

const int INT_SIZE = 4;
const int STRING_LENGTH = 32;
struct Data
{
   int nInt1;
   int nInt2;
   char czString[STRING_LENGTH];
};

...

FILE* pFile = fopen("filename.bin", "wb");
Data data;
// do stuff

fwrite(&data.nInt1, INT_SIZE, 1, pFile);
fwrite(&data.nInt2, INT_SIZE, 1, pFile);
fwrite(&data.czString, 1, STRING_LENGTH, pFile);

...

Will this actually work?  Will this write the lower 32 bits of an 
int if it is 64 bits?  If not, how can I guarantee it will write the 
lower 32 bits?

Thanks

Pete

Reply via email to