gpt4 book ai didi

c - 目录中文件的链接列表,最后附加

转载 作者:行者123 更新时间:2023-11-30 16:56:48 25 4
gpt4 key购买 nike

我正在尝试刷我的链表概念。作为一个例子,我试图创建一个包含目录文件的链接列表,按序列顺序。

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

这似乎总是以段错误结束。

最佳答案

正如 WhozCraigh 所说,每次 fullpath 时都必须 malloc,否则每次迭代都会被销毁。

这将完成这项工作:

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

关于c - 目录中文件的链接列表,最后附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com