2015-06-17 84 views
2

我試圖讀取文件中的特定行並將其添加到鏈接列表中,然後將其打印出來。
代碼波紋管:當print_list是誰跑會打印是最後一個條目的唯一的事爲什麼我的鏈表只打印最後一項?

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct list { 
    int uid; 
    char* uname; 
    struct list* next; 
}node; 



void push(node ** head, int uid ,char* uname) { 
    node * new_node; 
    new_node = malloc(sizeof(node)); 
    new_node->uid = uid ; 
    new_node->uname=uname;; 
    new_node->next = *head; 
    *head = new_node; 
} 


void print_list(node *head) { 
    node * current = head; 
    while (current != NULL) { 
     printf("%u:%s\n", current->uid,current->uname); 
     current = current->next; 
    } 
} 


int main(int argc, char **argv){ 

    node *current=NULL; 
    FILE *fp=fopen(argv[1],"r"); 
    if (fp==NULL){ 
     perror("Failed to open file"); 
     exit(EXIT_FAILURE); 
    } 
    char s[1024]; 
    const char token[2]=":"; 
    char *stoken; 
    while(!feof(fp)){ 
     int count=0; 
     int tempint; 
     char* tempchar=malloc(sizeof(char)); 
     fgets(s, 1024, fp); 
     stoken = strtok(s,token); 
     current=malloc(sizeof(node)); 
     while(stoken != NULL){ 
      if (count==0){ 
       tempchar=stoken; 
      } 
      if (count==2){ 
       sscanf(stoken,"%d",&tempint); 
      } 
      count++; 
     stoken=strtok(NULL,token); 
     } 
     push(&current,tempint,tempchar); 
    } 
    fclose(fp); 
    print_list(current); 
} 

我的問題是。

此輸入:

hello:asd:123:foo:ar 

hi:proto:124:oo:br 

hey:qwe:321:fo:bar 

其獲取打印的唯一的事情是

321:hey 

是我推至極是錯還是我print_list?

+1

我認爲有必要時跳過的空白行存在。和'while(!feof(fp)){' - >'while(fgets(s,1024,fp)){ – BLUEPIXY

回答

2

問題是您對待strtok的結果的方式:您正在將其值設置到節點中,而不是複製它。

添加節點時進行的name副本:

void push(node ** head, int uid ,char* uname) { 
    node * new_node; 
    new_node = malloc(sizeof(node)); 
    new_node->uid = uid; 
    new_node->uname=malloc(strlen(uname)+1); 
    strcpy(new_node->uname, uname); 
    new_node->next = *head; 
    *head = new_node; 
} 

你也應該看看,你是在main功能使用tempchar的方式。您爲單個字符分配一個空間,該空間會被strtok的結果寫入,並泄漏malloc -ed的內存。

0

這是因爲你總是在push()功能覆蓋head,你應該讓NULL開始,然後檢查它是否是NULL在第一時間並分配給它的第一個節點,然後不reassing什麼呢,你的程序因此也有內存泄漏。

此外,你是malloc() ing節點外的功能,然後在函數內再次,這會導致另一個內存泄漏。

您還應該檢查malloc()是否返回NULL,指示系統內存不足時發生錯誤,取消引用NULL指針是未定義的行爲。

而且最後要注意,你必須訪問目標變量之前檢查scanf()的返回值,或將再次導致不確定的行爲。

0

變化類似如下

char* tempchar;//=malloc(sizeof(char)); 
fgets(s, 1024, fp); 
stoken = strtok(s,token); 
//current=malloc(sizeof(node));//don't update like this 
while(stoken != NULL){ 
    if (count==0){ 
     tempchar=strdup(stoken);//malloc and strcpy 
相關問題