You could do something like this:
Code:
int write_persons_list( char *filename, PERSON_PTR pptr )
{
PERSON_PTR p;
FILE *f;
uint32_t count;
if ( ! ( f = fopen( filename "w" ) ) )
return 0;
count = 0;
if ( fwrite( &count, sizeof count, 1, f ) != 1 )
{
error:
fclose( f );
// delete the file in case of error!
unlink( filename );
return 0;
}
p = pptr;
while ( p )
{
// don't write p->next!
if ( fwrite( p, offsetof(PERSON,next), 1, f ) != 1 )
goto error;
p = p->next;
count++;
}
// Write the number of elements...
fseek( f, 0, SEEK_SET );
if ( fwrite( &count, sizeof count, 1 f ) != 1 )
goto error;
fclose( f );
return 1;
}
// Example call:
//
// PERSON_PTR *plist;
// if ( ! read_persons_list( "./list.bin", &plist ) ) { ... error handling... }
int read_persons_list( char *filename, PERSON_PTR *pp )
{
PERSON *p;
FILE *f;
uint32_t count;
if ( ! ( f = fopen( filename, "r" ) ) )
return 0;
if ( fread( &count, sizeof count, 1, f ) != 1 )
{
error:
fclose( f );
return 0;
}
if ( count == 0 )
goto error;
if ( ! ( *pp = malloc( count * sizeof( PERSON ) ) )
goto error;
p = *pp;
while ( count-- )
{
// don't read p->next!
if ( fread( p, offsetof( PERSON, next ), 1, f ) != 1 )
{
free( *pp );
goto error;
}
p->next = ++p;
}
// the last one must be NULL.
(p - 1)->next = NULL;
fclose( f );
return 1;
}