【问题标题】:Scan all files in Linux using C [duplicate]使用C扫描Linux中的所有文件[重复]
【发布时间】:2017-06-27 12:51:18
【问题描述】:

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

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”很多次, 有人知道为什么会这样吗?

【问题讨论】:

  • 你必须跳过像 .. 和 .当de-&gt;d_name...
  • 首先有点无关的仅供参考:dirent 结构已经包含一个类型,可用于查看条目是否为目录,无需 stat 调用。然后是主要部分:d_name 中的名称不是完整路径。您需要将其附加到pathus 中的当前路径。
  • 如果你想省点麻烦,看看man 3 ftw
  • 确保在访问path_stat.st_mode之前检查stat的返回值
  • 删除dr ==NULL if 子句中的exit(1);,如果你得到一个权限被拒绝的错误,它应该报告错误并移动到下一个文件或目录。一件事。不要使用 printf 向标准输出报告错误,使用 fprintf

标签: c linux


【解决方案1】:

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

如果您在运行此程序时位于/home/danny/src/,并在列出/ 时找到dev,则您不能opendir("dev"),这意味着/home/danny/src/dev,而不是/dev

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-05
    • 2013-05-21
    • 2017-01-04
    • 2016-03-23
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多