centos

CentOS readdir中的文件属性获取

小樊
52
2025-08-14 20:06:42
栏目: 智能运维

在 CentOS 系统中,你可以使用 readdir 函数来读取目录中的文件和子目录

以下是一个简单的示例,展示了如何使用 readdir 函数获取目录中的文件属性:

#include <stdio.h>
#include <stdlib.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) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

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

    while ((entry = readdir(dir)) != NULL) {
        // 获取文件的完整路径
        char path[PATH_MAX];
        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        // 获取文件属性
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 输出文件名和文件类型
        printf("%s - ", entry->d_name);
        if (S_ISREG(file_stat.st_mode)) {
            printf("Regular file\n");
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("Directory\n");
        } else if (S_ISCHR(file_stat.st_mode)) {
            printf("Character device\n");
        } else if (S_ISBLK(file_stat.st_mode)) {
            printf("Block device\n");
        } else if (S_ISFIFO(file_stat.st_mode)) {
            printf("FIFO\n");
        } else if (S_ISSOCK(file_stat.st_mode)) {
            printf("Socket\n");
        } else {
            printf("Other\n");
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后使用 readdir 函数读取目录中的所有条目。对于每个条目,它使用 stat 函数获取文件属性,并根据文件类型输出相应的信息。

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

gcc -o list_directory list_directory.c

现在你可以使用这个程序来列出目录中的文件及其属性,例如:

./list_directory /path/to/directory

0
看了该问题的人还看了