2015-02-09 25 views
0

正如我目前的功能,我只能讀取文件中的第一組數據。我相信這是因爲它不能按照我希望的方式運行,但它也可能是由於打印列表功能不佳造成的,但我不確定。我非常喜歡使用動態內存,所以忍受着我。將數據添加到來自文件的雙向鏈接列表中

從文件加載

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; 
+1

http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – Gopi 2015-02-09 05:38:30

+0

@Gopi如果我不使用feof,那麼我可以用什麼來告訴我是否在文件結尾? – user3482104 2015-02-09 05:44:30

+0

關於在C中對malloc()1)的調用,不要從malloc(和系列)轉換返回的值2)總是檢查返回值以確保insertNode函數中的操作成功(!= NULL) – user3629249 2015-02-09 05:48:14

回答

1

函數調用insertNode(head,head->data);看起來很奇怪。第二個參數必須是不是來自head的數據,否則頭中的數據將被重新寫入任何新記錄。

因此在load函數內部爲Record分配內存並且不要使用head->data

+0

所以就這樣? tempRecord =(記錄*)malloc的(的sizeof(記錄));然後將tempRecord傳遞給instertNode? – user3482104 2015-02-09 06:31:06

+0

是的。我的意思是這個。但是,代碼 – VolAnd 2015-02-09 06:34:33

+0

中可能需要進行其他更改。因此,這可能或可能不起作用,但我需要切換到下一個節點,以便我可以存儲下一組數據。我在評論的主體中標出了這一行。 – user3482104 2015-02-09 06:59:43