gpt4 book ai didi

c - 如何使用c在Linux中查找目录?

转载 作者:太空狗 更新时间:2023-10-29 11:29:44 25 4
gpt4 key购买 nike

我正在 linux 中制作一个 c 程序,用户可以在其中输入要查找的目录名称。我以下是我编写但未获得正确输出的代码。我正在搜索所有目录,直到找到目录。
我只是一个初学者。

#include<unistd.h>
#include<dirent.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<errno.h>

void findDir(char *dir, char *name)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;

if((dp = opendir(dir)) == NULL)
{
printf("\ncan not open directory: %s", name);
printf("\nDescription: %s", strerror(errno));
return;
}

chdir(dir);

while(( entry = readdir(dp)) != NULL)
{
lstat( entry->d_name, &statbuf);
if(S_ISDIR( statbuf.st_mode))
{
if( strcmp(name,entry->d_name) == 0)
{
printf("Dir found");
return;
}
findDir(entry->d_name, name);
}
}
chdir("..");
closedir(dp);
}

void main(int argc, char *argv[])
{
if( argc != 2 )
{
printf("Error");
}
else
{
findDir("/home", argv[1]);
}
}

请帮忙!!我在将 Documents 作为参数时得到以下输出。实际上程序变得无限,我重复得到以下输出。这只是输出的一小部分。

can not open directory: Documents
Description: Too many open files
can not open directory: Documents
Description: Too many open files
can not open directory: Documents
Description: Too many open filesDir found

最佳答案

问题是 readdir() 不可可重入。它依赖于一个内部缓冲区,当您递归时,该缓冲区将被覆盖。如果你使用的是 POSIX 标准,你可以尝试 readdir_r这是可重入的。

或者,您可以在开始递归之前将目录读入列表,然后一次一个地处理列表中的项目。这样,在尝试深入目录树的下一层之前,您已经阅读了整个目录,并且当前层的条目不会因更深层次的覆盖而丢失。

关于c - 如何使用c在Linux中查找目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16344347/

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