我一直在尝试在二进制文件和链表之间进行读写。有人可以解释我做错了什么吗?
节省:
currentContact = firstContact;
while( currentContact != NULL )
{
fwrite (currentContact->firstName, sizeof currentContact->firstName, 1, myFile);
fwrite (currentContact->surname, sizeof currentContact->surname, 1, myFile);
fwrite (¤tContact->age, sizeof (int), 1, myFile);
fwrite (currentContact->telephone, sizeof currentContact->telephone, 1, myFile);
currentContact = currentContact->next;
}
加载:
fread( &numContacts, sizeof( int ), 1, myFile );
newContact = realloc( newContact, sizeof( struct Contact ) * 1 );
countFile = 1;
while (fread(newContact, sizeof( struct Contact ), 1, myFile))
{
fread(newContact->firstName, sizeof newContact->firstName, 1, myFile);
fread(newContact->surname, sizeof newContact->surname, 1, myFile);
fread((&newContact->age), sizeof (int), 1, myFile);
fread(newContact->telephone, sizeof newContact->telephone, 1, myFile);
if (countFile == 1)
{
firstContact = newContact;
newContact = NULL;
}
else
{
currentContact = firstContact;
count = 0;
while( count != countFile )
{
if( strcmp( newContact->surname, currentContact->surname ) < 0 )
{
newContact->next = currentContact->next;
currentContact->next = newContact;
}
currentContact = currentContact->next;
}
newContact = NULL;
}
countFile++;
}
fclose( myFile );
编辑:
应用一些更改后,通过循环再次解析文件的第二次解析仍然存在错误......
newContact = realloc( newContact, sizeof( struct Contact ) * numContacts );
countFile = 1;
while (countFile != numContacts + 1)
{
fread(newContact, sizeof (struct Contact), 1, myFile);
if (countFile == 1)
{
firstContact = newContact;
newContact = NULL;
}
else
{
currentContact = firstContact;
count = 0;
while( count != countFile )
{
if( strcmp( newContact->surname, currentContact->surname ) < 0 )
{
newContact->next = currentContact->next;
currentContact->next = newContact;
}
currentContact = currentContact->next;
}
newContact = NULL;
}
countFile++;
}