我在当前目录中搜索目录,如果我在一个目录中,我进入并再次搜索目录和文件,但我找不到问题。我总是得到相同的结果和一些特定的目录。在代码中,我在数组中获取目录名称并打印出来。结果如下所示;
direc Num (except parent and curr) : 6
/home/sabri/Desktop/Test/Untitled Folder 3
/home/sabri/Desktop/Test/Untitled Folder 3
/home/sabri/Desktop/Test/Untitled Folder 3
/home/sabri/Desktop/Test/Untitled Folder 3
/home/sabri/Desktop/Test
/home/sabri/Desktop/Test/Untitled Folder 4
/home/sabri/Desktop/Test/Untitled Folder 4
/home/sabri/Desktop/Test/Untitled Folder 4
但我的目录是;
Untitled Folder 1
Untitled Folder 2
Untitled Folder 3
Untitled Folder 4
Untitled Folder 5
int listFilesIndir(char *currDir)
{
struct dirent *direntp;
char newDir[20][250];
DIR *dirp;
int x ,y =0,i=0 ;
if ((dirp = opendir(currDir)) == NULL)
{
perror ("Failed to open directory");
return 1;
}
while ((direntp = readdir(dirp)) != NULL)
{
printf("%s\n", direntp->d_name);
if(direntp->d_type == DT_DIR)
{
y++;
chdir(direntp->d_name);
getcwd(newDir[i],250);
listNewDir(direntp->d_name);
i++;
}
}
printf("direc Num (except parent and current) : %d\n",y-2 );
for ( i = 0; i < 10; ++i)
{
printf("%s\n", newDir[i]);
}
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
return 0;
}
int listNewDir(char *currDir)
{
struct dirent *direntp;
DIR *dirp;
if ((dirp = opendir(currDir)) == NULL)
{
perror ("Failed to open directory");
return 1;
}
while ((direntp = readdir(dirp)) != NULL)
printf("%s\n", direntp->d_name);
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
return 0;
}
答案 0 :(得分:0)
你需要跳过'。'和'..'条目。你也不应该做chdir和getcwd。只需将目录名称传递给listNewDir函数,即可打印该目录中的文件。 (如果要保存名称,可以将名称strcpy到newDir。)
此外,for循环最多只能达到10,而newDir只适用于20个条目。我认为这些仅用于测试。