バイナリファイルとリンクリストの間で書き込みと読み取りを試みてきました。誰かが私が間違っていることを説明できますか?
保存する:
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 );
編集:
いくつかの変更を適用した後でも、ループを介した2回目の解析でエラーが発生し、ファイルが再びフレッドされます...
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++;
}