温馨提示×

CentOS readdir中的时间戳信息如何获取

小樊
41
2025-12-25 12:05:14
栏目: 智能运维

在 CentOS 系统中,你可以使用 readdir 函数来读取目录内容

以下是一个简单的示例,展示了如何使用 readdir 函数读取目录内容并获取文件的时间戳信息:

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

        // 输出文件名和时间戳信息
        char time_buf[26];
        ctime_r(&file_stat.st_mtime, time_buf);
        time_buf[strcspn(time_buf, "\n")] = 0; // 删除换行符
        printf("%s: %s", entry->d_name, time_buf);
    }

    closedir(dir);
    return 0;
}

这个示例程序会打开当前目录,读取目录中的所有文件和子目录,并使用 stat 函数获取每个文件的详细信息。然后,它将输出文件名和最后修改时间。

注意:这个示例程序使用了 POSIX 标准函数,应该在大多数 Unix-like 系统(包括 CentOS)上运行正常。

0