正如我目前的功能,我只能讀取文件中的第一組數據。我相信這是因爲它不能按照我希望的方式運行,但它也可能是由於打印列表功能不佳造成的,但我不確定。我非常喜歡使用動態內存,所以忍受着我。將數據添加到來自文件的雙向鏈接列表中
從文件加載
void load(FILE *file, Node *head)
{
char tempArtist[30] = {'\0'}, tempAlbum[30] = {'\0'}, tempTitle[30] = {'\0'}, tempGenre[30] = {'\0'}, tempSpace = '\0';
SongLength *tempLength = NULL;
char tempPlay[100] = {'\0'}, tempRating[6] = {'\0'}, tempMins[3] = {'\0'}, tempSecs[3] = {'\0'};
tempLength = (SongLength *)malloc(sizeof(SongLength));
while (!feof(file))
{
while (head->pNext == NULL) // Here is where I need to shift to the next node
{
fscanf(file, "%s", &tempArtist);
fscanf(file, "%c", &tempSpace);
strcpy(tempLength->mins, tempMins);
strcpy(tempLength->secs, tempSecs);
strcpy(head->data->artist, tempArtist);
strcpy(head->data->length->mins, tempLength->mins);
strcpy(head->data->length->secs, tempLength->secs);
insertNode(head, head->data);
}
}
free(tempLength);
}
插入到鏈表
void insertNode(Node *head, Record *data)
{
while(head->pNext == NULL)
{
head=head->pNext;
}
head->pNext=(Node*)malloc(sizeof(Node));
head->pNext->data = (Record*)malloc(sizeof(Record));
head->pNext->data->length=(SongLength*)malloc(sizeof(SongLength));
(head->pNext)->pPrev=head;
head=head->pNext;
head->data=data;
head->pNext=NULL;
}
打印的所有數據的列表(希望)
void display (Node *head)
{
while (head->pNext != NULL)
{
printf ("Artist: %s\n", head->data->artist);
printf ("Length(mm:ss) %s:%s\n", head->data->length->mins,head->data->length->secs);
head=head->pNext;
}
putchar ('\n');
}
我已經刪除了除fscanf()和printf()之外的所有內容以減少代碼。
的Structs
typedef struct songlength
{
char mins[3];
char secs[3];
}SongLength;
typedef struct record
{
char artist[30];
struct songlength *length;
}Record;
typedef struct node
{
struct node *pPrev;
struct record *data;
struct node *pNext;
}Node;
http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – Gopi 2015-02-09 05:38:30
@Gopi如果我不使用feof,那麼我可以用什麼來告訴我是否在文件結尾? – user3482104 2015-02-09 05:44:30
關於在C中對malloc()1)的調用,不要從malloc(和系列)轉換返回的值2)總是檢查返回值以確保insertNode函數中的操作成功(!= NULL) – user3629249 2015-02-09 05:48:14