使用C扫描Linux中的所有文件

时间:2017-06-27 12:51:19

标签: c linux

我正在尝试扫描计算机中的所有文件,包括子目录中的文件。程序应该从根文件夹“/".

开始

logfind.c

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

int is_directory(const char *path) {
        struct stat path_stat;
        stat(path, &path_stat);
        return S_ISDIR(path_stat.st_mode);
}

void list_files(char *pathus) {
        struct dirent *de;

        DIR *dr = opendir(pathus);

        if (dr == NULL) {
                printf("Could not open current directory");
                exit(1);
        }

        while ((de = readdir(dr)) != NULL) {
                if (is_directory(de->d_name) > 0)
                        list_files(de->d_name);
                else
                        printf("%s\n", de->d_name);
        }

        closedir(dr);
}

int main(int argc, char **argv) {
        list_files("/");
        return 0;
}

运行时我得到的输出基本上是“logfind.c”多次, 任何人都知道为什么会这样?

1 个答案:

答案 0 :(得分:2)

这是因为您的代码中没有任何内容可以更改过程&#39;当前目录,或构建要扫描的目录的完整路径。

如果您在/home/danny/src/运行时遇到dev,并在列出/时找到opendir("dev"),则无法/home/danny/src/dev,那就是&#39} ; d表示/dev,而不是{{1}}。