gpt4 book ai didi

c - 在 Ubuntu 中打印目录时遇到段错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:19:45 35 4
gpt4 key购买 nike

我已经研究这段代码一段时间了,但我无法找出问题所在。这个想法是打印出给定目录中的所有目录和子目录(为了测试目的而硬编码)。但是,我一直遇到段错误。

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

struct item
{
char location[256];
int level;
int order;
bool isExpanded;
struct item *next;
};

struct item *headNode = NULL;
struct item *currentNode = NULL;
struct item *loopNode = NULL;
static int currentLevel = 1;
static int currentOrder = 1;
bool finished = false;
char currentLocation[256];

void addNode(char location[256])
{
struct item *ptr = (struct item*)malloc(sizeof(struct item));
ptr->level = currentLevel;
ptr->order = currentOrder;
ptr->isExpanded = false;
int x;
for(x = 0; x < strlen(location); x++)
ptr->location[x] = location[x];

ptr->location[x] = '\0';
ptr->next = NULL;

currentNode->next = ptr;
currentNode = ptr;
}

int main(int argc, char *argv[])
{
struct dirent *pDirent;
DIR *pDir;
argv[1] = "/home/collin/Documents";
char temp[256];

pDir = opendir (argv[1]);
if (pDir == NULL)
{
printf ("Cannot open directory '%s'\n", argv[1]);
return 1;
}
closedir (pDir);

headNode = (struct item*)malloc(sizeof(struct item));
headNode->level = currentLevel;
headNode->order = currentOrder;
headNode->isExpanded = false;
int x;
for(x = 0; x < strlen(argv[1]); x++)
{
headNode->location[x] = argv[1][x];
currentLocation[x] = argv[1][x];
}

headNode->location[x] = '\0';
currentLocation[x] = '\0';
headNode->next = NULL;

currentNode = headNode;

while(!finished)
{
finished = true;
loopNode = headNode;
currentLevel++;
currentOrder = 1;
while(loopNode != NULL)
{
if(!loopNode->isExpanded)
{
pDir = opendir (loopNode->location);
for (x = 0; x < strlen(loopNode->location); x++)
{
currentLocation[x] = loopNode->location[x];
}
currentLocation[x] = '\0';

while ((pDirent = readdir(pDir)) != NULL)
{
finished = false;
if(!(!strcmp(pDirent->d_name, ".")||!strcmp(pDirent->d_name, "..")))
{
sprintf(temp, "%s/%s", currentLocation, pDirent->d_name);
addNode(temp);
currentOrder++;
}
}
closedir (pDir);
loopNode->isExpanded = true;
}
loopNode = loopNode->next;
}
}

currentNode = headNode;
while (currentNode != NULL)
{
printf ("%d:%d:%s\n", currentNode->level, currentNode->order, currentNode->location);
currentNode = currentNode->next;
}

return 0;
}

最佳答案

您没有检查 opendir 的参数是一个目录,也没有尝试在文件上调用它。检查 opendir 返回值,或者检查您请求打开的文件实际上是一个目录,或者 - 甚至更好 - 两者都是。

关于c - 在 Ubuntu 中打印目录时遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18975892/

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