centos

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

小樊
33
2025-04-12 20:18:08
栏目: 智能运维

在 CentOS 系统中,你可以使用 readdir 函数来读取目录中的文件和子目录。为了获取文件属性,你需要结合使用 dirent.hsys/stat.h 头文件中的函数和结构体。以下是一个简单的示例,展示了如何使用 readdir 获取 CentOS 文件属性:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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 file_path[1024];
        snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

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

    // 关闭目录
    closedir(dir);

    return 0;
}

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

注意:在编译此程序时,请确保链接到正确的库。例如,使用 gcc 编译器时,可以使用以下命令:

gcc your_file.c -o your_program

your_file.c 替换为你的源代码文件名,将 your_program 替换为你想要生成的可执行文件名。

0
看了该问题的人还看了