• C

Write struct to file

How do I write the following struct to a binary file in the correct byte order?  (Linux platform)
For example, the file should list the struct in the order shown below.

struct test_id      {
      unsigned int f1:3;
      unsigned int f2:4;
      unsigned int f3:5;
      unsigned int f4:8;
      unsigned int f5:4;
      unsigned int f6:12;
} test;

      FILE *fp = fopen("testfile", "w");
      test.f1= 2;
      test.f2 = 0;
      test.f3 = 22;
      test.f4= 23;
      test.f5 = 4;
      test.f6= 200;
Who is Participating?
manish_regmiConnect With a Mentor Commented:


#define htole_w(val) (val)
#define htole_d(val) (val)

#define htole_w(val) ((val << 8) & 0xFF00 | ((val >> 8) &0xFF)) for 16 bit


Have you tried fwrite()? The following MAY work. (I haven't tested it.)

fwrite(&test, sizeof( test ), 1, fp);
The order that the elements are stored in memory is probably OS and/or compiler dependent, too.
Turn Raw Data into a Real Career

There’s a growing demand for qualified analysts who can make sense of Big Data. With an MS in Data Analytics, you can become the data mining, management, mapping, and munging expert that today’s leading corporations desperately need.

dark_archonConnect With a Mentor Commented:
I've now tested it, and it works. Just use fread() to read it all into another struct:

fread( &test, sizeof( test ), 1, fp );
>> 've now tested it, and it works. Just use fread() to read it all into another struct:
I wont always work.
Have you tried the program to store in Big Endian machine and program to retrieve in little endean machine.

You need to take a design decision to store the multibyte values in either bigendean or Little endean.

1) then before writing convert your multibyte data to your endeaness of choice.
You should make a macro to convert from host byte order to you chosen byte order.

2) write it to a file.

While retrieveing,
1) read from the disk.
2) convert from on disk byte order to host byte order.

Can u use some padding to your structure elements and make 8 16 or 32 bit values.

Manish Regmi
jeweeAuthor Commented:
Thank you for the recommendations.  I will have to store it on a little endian machine.

I have little experience with this.  Could you provide me with sample code for the conversion?

Also, in regards to padding - I could possibly insert 0 filled padding at the end.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.