我正在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作为参数时,我得到了以下输出。实际上,程序会进入无限循环,并且我会反复得到以下输出。这只是输出的一小部分。
无法打开目录:Documents
描述:文件打开过多
无法打开目录:Documents
描述:文件打开过多
无法打开目录:Documents
描述:文件打开过多