By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,148 Members | 1,342 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,148 IT Pros & Developers. It's quick & easy.

Binray File Reading and Writing a structure..portable, backward compatible

P: 1
i want your inputs for my Problem. i want to write some structure info in binary format into a file and read it back.i better explain with an example.
I have a structure struct A{int a, int b} in my current version of software and write into a file.
in the next version of software my struct might change to struct A1{int a,int b,int c}. so using this software too i should be able to work with my old version files.

and another constraint is the file should be readble both in linux and windows.

Thanks in Advance for all your inputs.

Nov 2 '06 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 8,916
OK you need to separate the data structure in the file and the data structure in the program.

You need to version number your file so that you can tell if you are reading a file with an older format, I normally reserve the first 2 bytes of the file to hold the version number.

You should only read and write bytes (char) to the file. If you read and write anything of more than 1 byte you will get a portability issue, this isn't to say that you can't read/write several bytes at a time but they must be in file structure.

For instance to write a 4 byte int i to a file

fwrite( &i, sizeof int, 1, fout );

is bad because you are relying on the byte ordering of the integer in the computers memory and this may be different on another computer. This is the way to do it

unsigned int *pu = (unsigned int *)&i;

fwrite( (unsigned char)(((*pu)>>24)&0xFF), 1, 1, fout );
fwrite( (unsigned char)(((*pu)>>16)&0xFF), 1, 1, fout );
fwrite( (unsigned char)(((*pu)>>8)&0xFF), 1, 1, fout );
fwrite( (unsigned char)((*pu)&0xFF), 1, 1, fout );

This will work on any machine because I am specifically writing the individual bytes of the integer in a known order.

Reading the data has to be done in a similar manor.

Alternitively write and read the values as text
Nov 2 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.