O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code Sample 12.6: Writing a union to File

In other words, although the memory requirement for a union is equal to the size of the largest data member, unless you write the whole union as an object to the file, the size taken will only be the same as the member you choose to write.

The following code snippet is taken from the UnionTest.c program:

   hFile = fopen ( "ulw.txt", "w" );
fwrite( &uLongWord, sizeof(longword), 1, hFile);
fclose(hFile);

Note that the size of the union is provided in the second parameter of the fwrite function call. So the whole four bytes of the union will be written out. This is an example of writing the instance of the union as an object.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required