在Linux中,readdir
函數用于讀取目錄中的條目。如果你想要獲取文件的修改時間,你需要使用stat
函數來獲取文件的詳細信息。以下是一個簡單的示例,展示了如何使用readdir
和stat
函數來獲取目錄中文件的修改時間:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.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) {
// 跳過當前目錄和上級目錄的特殊條目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 構建文件的完整路徑
char file_path[PATH_MAX];
snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);
// 獲取文件的詳細信息
if (stat(file_path, &file_stat) == -1) {
perror("stat");
closedir(dir);
return EXIT_FAILURE;
}
// 打印文件的修改時間
char time_buf[26];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
printf("%s: %s\n", entry->d_name, time_buf);
}
closedir(dir);
return EXIT_SUCCESS;
}
這個程序接受一個目錄作為命令行參數,然后使用readdir
函數讀取目錄中的條目。對于每個條目,它使用stat
函數獲取文件的詳細信息,包括修改時間(st_mtime
字段)。然后,它使用strftime
函數將修改時間格式化為易讀的字符串,并將其打印出來。
編譯并運行這個程序,你將看到目錄中每個文件的修改時間。