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

标签 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”, 有人知道为什么会发生这种情况吗?

最佳答案

发生这种情况是因为代码中没有任何内容可以更改进程的当前目录,或构建要扫描的目录的完整路径。

如果您在运行此命令时位于 /home/danny/src/ 中,并在列出 / 时找到 dev,您可以't opendir("dev"),这意味着 /home/danny/src/dev,而不是 /dev

关于c - 使用C扫描Linux中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780773/

相关文章:

c - ltrace 和 strace 工具中的行号信息

c - 套接字编程-如何让服务器只存储数字

linux - 如何在 Linux 上的 shell 脚本中获取屏幕分辨率

c++ - libarb.so : cannot open shared object file: No such file or directory

c - 如何使用指针更改字符串中的字符?

C段错误在递归函数中调用strcat

c - 如何读取文件中用逗号分隔的 2 个浮点值并将其存储到两个数组中,其中每个 float 存储在一个数组中

linux - POSIX glob -- 如何匹配一个或多个 [ :digit:]

c - u_int64_t 在 32 位机器上可用吗?

linux - 通过替换 .so 文件更新 Apache 身份验证模块