centos

如何在CentOS中使用readdir获取文件属性

小樊
45
2025-09-13 22:54:06
栏目: 智能运维

在 CentOS 中,你可以使用 C 语言的 dirent.h 库中的 readdir 函数来读取目录中的文件和子目录

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

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;

    // 打开目录
    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

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

        // 获取文件或目录的完整路径
        char path[1024];
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 获取文件或目录的属性
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            exit(EXIT_FAILURE);
        }

        // 输出文件名和属性
        printf("Name: %s\n", entry->d_name);
        printf("Size: %ld bytes\n", file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
        printf("\n");
    }

    // 关闭目录
    closedir(dir);

    return 0;
}

这个程序首先打开当前目录(.),然后使用 readdir 函数读取目录中的每个条目。对于每个条目,它使用 stat 函数获取文件或目录的属性,并输出文件名、大小和最后修改时间。

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

gcc list_directory.c -o list_directory

这将生成一个名为 list_directory 的可执行文件。运行该文件以查看当前目录中的文件和子目录及其属性:

./list_directory

0
看了该问题的人还看了