debian

如何用Debian readdir过滤文件

小樊
36
2025-06-25 10:05:39
栏目: 智能运维

在Debian系统中,你可以使用readdir函数来读取目录中的文件。为了过滤文件,你可以在遍历目录时检查每个文件的属性,然后根据需要处理或忽略它们。以下是一个简单的示例,展示了如何使用C语言和dirent.h库来实现这个功能:

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    char *dir_path = argv[1];
    struct dirent *entry;
    DIR *dp = opendir(dir_path);

    if (dp == NULL) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dp)) != NULL) {
        // 过滤掉当前目录(".")和上级目录("..")
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 获取文件的完整路径
        char file_path[PATH_MAX];
        snprintf(file_path, sizeof(file_path), "%s/%s", dir_path, entry->d_name);

        // 获取文件状态
        struct stat file_stat;
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 根据需要过滤文件,例如:只显示普通文件
        if (S_ISREG(file_stat.st_mode)) {
            printf("%s\n", file_path);
        }
    }

    closedir(dp);
    return 0;
}

这个示例程序接受一个目录路径作为参数,然后读取该目录中的所有文件。它使用readdir函数遍历目录,并使用stat函数获取每个文件的状态。在这个例子中,我们只打印出普通文件(非目录、非符号链接等)的路径。你可以根据需要修改过滤条件。

要编译这个程序,请将其保存为list_files.c,然后在终端中运行以下命令:

gcc list_files.c -o list_files

现在你可以使用这个程序来列出指定目录中的文件,并根据需要过滤它们。例如:

./list_files /path/to/directory

0
看了该问题的人还看了