2016-10-01 14 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

2つのこと:

この

は仕事を行います。 (1)あなたの文字列の長さの計算に恥ずかしがり屋であり、(2) 'last-> name = full_path;'は*良い*とは言えません。ループを繰り返すたびに自動的に 'full_path'が破棄され、ループが終了すると、無効な名前のポインタでいっぱいのリストが作成されます。作成している名前の動的*コピー*を作成する必要があります。 – WhozCraig

+0

@WhozCraig(1)ああそう! (2)これを訂正する正しい方法は何でしょうか? – Amit

+0

@WhozCraig nvm、動的コピー。それを読まなかった! – Amit

答えて

0

WhozCraighは、毎回にするか、または各繰り返しでそれが破壊されると言います。

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; 
} 
関連する問題