我一直在嘗試在二進制文件和鏈接列表之間進行讀寫操作。有人能解釋我做錯了什麼嗎?將二進制文件讀取到鏈接列表
節省:
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);
編輯:
應用一些變化,但仍然通過它去FREAD迴路中的第二解析錯誤後該文件再次...
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++;
}
我已經改變它,以便它爲充分接觸分配存儲器,而該單個元件:的fread(newContact,的sizeof(結構聯繫),1,MYFILE); 無論如何這個文件是按順序保存的,所以每個新條目都應該是列表中的最後一個條目,所以最後一個問題應該不成問題。 – user1949687
最後一個問題仍然是一個問題 - 在調試器中逐步完成。新項目不會被添加到列表中。 –
感謝您的幫助,我已經設法解決了。在您的幫助和調試器中,我設法解決了多個愚蠢的錯誤。 – user1949687