Amit Amit - 2 months ago 7
C Question

linked list of files in a directory with append at last

I am trying to brush my linked list concepts. As an example I am trying to create a linked list with files of a directory, in serial order.

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;
}


This seems to always end with a seg fault.

Answer

As WhozCraigh say you have to malloc each time fullpath, or at each iteration it will be destroyed.

This will do the job:

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;
}
Comments