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.3: File I/O with structs as Memory Objects

When you read the data back in from the file, you can fill up an array or dynamically reallocate memory to store the entries in. Using a simple array, you could write code such as:

sAddressEntry oAddressBook[MAX_ENTRIES];

// 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;

do
{
  fread ( &oAddressBook[nRef],
						sizeof(sAddressEntry), 1, hFile );

  nRef++;
} while ( ftell (hFile) > lSize (hFile) );

This short snippet introduces a simple method that establishes the file size and then checks to see that you have not reached it. This allows you to know when you should end the file-reading ...

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