2016-10-01 41 views
0

我想刷我的鏈接列表概念。作爲一個例子,我試圖以連續的順序創建一個包含目錄文件的鏈表。鏈接的目錄中的文件的最後追加

struct node *head = NULL; 
    struct node *prev = head; 

    DIR *d; 
    struct dirent *dir; 
    d = opendir("/var/amit12/test1/"); 
    if(d) { 
     while ((dir = readdir(d)) != NULL) { 
      if(dir->d_type == DT_REG) { 
       struct node *last = (struct node*) malloc(sizeof(struct node)); 
       char full_path[18 + strlen(dir->d_name)]; 
       strcpy(full_path, "/var/amit12/test1/"); 
       strcat(full_path, dir->d_name); 
       last->song_id = open(full_path, O_RDONLY); 
       last->name = full_path; 
       last->next = NULL; 
       if(head == NULL) { 
        head = last; 
        prev = last; 
       } else { 
        prev->next = last; 
        prev = last; 
       } 
       //prev.next = &last; 
       //prev = last; 
       printf("%s\n", dir->d_name); 
      } 
     } 
     closedir(d); 
    } 

printf("printing\n"); 

    struct node *root = head; 

    while(root != NULL) { 
     printf("%s\n", root->name); 
     root = root->next; 
    } 

這似乎總是以seg故障結束。

+3

兩件事情。 (1)你害怕你的字符串長度計算,並且(2)'last-> name = full_path;'*不會預示好。循環的每次迭代破壞自動var'full_path',一旦循環終止,你有一個充滿無效名稱指針的列表。您需要製作您正在創建的名稱的動態*副本。 – WhozCraig

+0

@WhozCraig(1)啊,對! (2)糾正這個問題的正確方法是什麼? – Amit

+0

@WhozCraig nvm,動態副本。沒有讀過! – Amit

回答

0

正如WhozCraigh所說,你必須每次fullpath,或者在每次迭代中它都會被銷燬。

這將做的工作:

struct node *head = NULL; 
struct node *prev = head; 
char *full_path = NULL; 

DIR *d; 
struct dirent *dir; 
d = opendir("/var/amit12/test1/"); 
if(d) { 
    while ((dir = readdir(d)) != NULL) { 
     if(dir->d_type == DT_REG) { 
      struct node *last = (struct node*) malloc(sizeof(struct node)); 
      full_path = strnew(strlen("/var/amit12/test1/") + strlen(dir->d_name); 
      strcpy(full_path, "/var/amit12/test1/"); 
      strcat(full_path, dir->d_name); 
      last->song_id = open(full_path, O_RDONLY); 
      last->name = full_path; 
      last->next = NULL; 
      if(head == NULL) { 
       head = last; 
       prev = last; 
      } else { 
       prev->next = last; 
       prev = last; 
      } 
      //prev.next = &last; 
      //prev = last; 
      printf("%s\n", dir->d_name); 
     } 
    } 
    closedir(d); 
} 

printf("printing\n"); 

struct node *root = head; 

while(root != NULL) { 
    printf("%s\n", root->name); 
    root = root->next; 
} 
相關問題