c - 如何递归列出所有目录?

标签 c linux

我的代码不工作。我需要显示作为命令行参数给出的目录内的所有目录。到目前为止,我已经试过了:

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

struct stat my_stat;

int searchDirectory (char *dirName);

int searchDirectory(char *dirName){
    struct dirent *pDirent;
    DIR *pDir;

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

    while ((pDirent = readdir(pDir)) != NULL){
        printf("%s\n", pDirent->d_name);
        stat(pDirent->d_name, &my_stat);
        if (S_ISDIR(my_stat.st_mode)){
            searchDirectory(pDirent->d_name);
            printf("Directory Found: %s\n", pDirent->d_name);
        }
    }

    return 0;
}

int main(int argc, char *argv[]){
    struct stat my_stat;


    if (lstat(argv[1], &my_stat) < 0){
        perror("stat error");
    }

    if (S_ISDIR(my_stat.st_mode)){ 
        printf("Directory found\n");
        searchDirectory(argv[1]);
    }

    return 0;
}

我不确定为什么,但出于某种原因,我的代码将普通文件作为目录读取,但 S_ISDIR(my_stat.st_mode)) 应该可以防止这种情况发生。知道哪里出了问题吗?

最佳答案

您遇到的问题是 pDirent->d_name 是相对于您当前列出的目录的,而您的进程有一个启动进程的工作目录。

要修复,在执行 opendir 之前连接目录的名称

int searchDirectory(char *dirName){
    ......
    while ((pDirent = readdir(pDir)) != NULL){
        printf("%s\n", pDirent->d_name);
        stat(pDirent->d_name, &my_stat);
        if (S_ISDIR(my_stat.st_mode)){
            // construct new path ....
            char * dirname = malloc(strlen(dirName)+strlen(pDirent->d_name)+2);
            strcat(strcat(strcpy(dirname,dirName),"/"),pDirent->d_name);
            searchDirectory(dirname);
            free(dirname)
            printf("Directory Found: %s\n", pDirent->d_name);
        }
     }
     .....

另请注意,您需要将 ... 目录作为代码的特殊情况处理,否则将以无限递归结束,因此您需要额外的处理这些的代码——参见 this question详情

关于c - 如何递归列出所有目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375157/

相关文章:

c - fprintf 不工作

linux - 如何捕获键盘事件并将监视器用作 Linux 上的文本显示?

Linux:环回接口(interface)上的传入数据包

linux - 什么Linux类相当于CStdioFile

regex - find 命令无法排除确切的正则表达式

java - 如何获取USB设备是连接在USB3.0还是USB2.0口

c - 在 C 编程中存储日志/错误消息

c - 使用 C 语言绘制 x-y 图

objective-c - NSLog iPhone中Objective-C的方法名

c - 在 C 中使用带有数组的循环