centos

CentOS readdir如何实现文件过滤

小樊
44
2025-04-24 23:02:23
栏目: 智能运维

在 CentOS 系统中,使用 readdir 函数可以读取目录中的文件。为了实现文件过滤,你可以在遍历目录时检查每个文件的属性,然后根据需要决定是否处理该文件。以下是一个简单的示例,展示了如何使用 readdir 函数和 dirent.h 库来实现文件过滤:

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;

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

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

        // 拼接文件名和路径
        char file_path[1024];
        snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);

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

        // 过滤条件:仅显示普通文件
        if (S_ISREG(file_stat.st_mode)) {
            printf("%s\n", file_path);
        }
    }

    closedir(dir);
    return 0;
}

在这个示例中,我们首先打开一个目录,然后使用 readdir 函数遍历目录中的所有文件。对于每个文件,我们使用 stat 函数获取文件的状态信息,然后检查文件类型是否为普通文件(S_ISREG)。如果是普通文件,我们将其路径打印出来。

你可以根据需要修改过滤条件,例如,你可以检查文件的扩展名、大小、修改时间等属性,以便仅显示符合特定条件的文件。

0
看了该问题的人还看了