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.4: Reading structs into a Dynamic Memory Block

You retain the same file management (size and end-of-file testing) as before, and the file read operation also remains the same. Therefore, you arrive at the following code:

sAddressEntry * pAddressBook;

// Get the file length
fseek ( hFile, 0, SEEK_END );
long int lSize = ftell ( hFile );
fseek ( hFile, 0, SEEK_SET );

// Read until the end of the file
int nRef = 0;
int nRead = 0;

pAddressBook = NULL; // No objects at first

do
{
   if ( pAddressBook == NULL )
   {
      pAddressBook = ( sAddressEntry * )
      malloc ( sizeof (sAddressEntry ) );
    }
    else
    {
      pAddressBook = ( sAddress Entry * )
      realloc ( sizeof (sAddressEntry) * nRef );
    }

    nRead = fread ( &oAddressBook[nRef], sizeof(sAddressEntry), 1, hFile ...

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