在編程中,readdir
函數通常用于讀取目錄中的條目。然而,readdir
本身并不直接提供文件的最后修改時間。要獲取文件的最后修改時間,你需要使用其他函數來獲取這個信息。
以下是在不同編程語言中獲取文件最后修改時間的示例:
dirent.h
和sys/stat.h
)#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");
return 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);
// 獲取文件的stat信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 轉換并打印最后修改時間
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
printf("File: %s, Last Modified: %s\n", entry->d_name, time_str);
}
closedir(dir);
return EXIT_SUCCESS;
}
os
和os.path
模塊)import os
import time
for entry in os.scandir('.'):
if entry.is_file():
# 獲取文件的最后修改時間
mod_time = os.path.getmtime(entry.path)
# 轉換并打印最后修改時間
print(f"File: {entry.name}, Last Modified: {time.ctime(mod_time)}")
fs
模塊)const fs = require('fs');
const path = require('path');
fs.readdir('.', (err, files) => {
if (err) {
return console.error('Unable to scan directory: ' + err);
}
files.forEach(file => {
const filePath = path.join(__dirname, file);
fs.stat(filePath, (err, stats) => {
if (err) {
return console.error('Unable to retrieve file stats: ' + err);
}
// 轉換并打印最后修改時間
console.log(`File: ${file}, Last Modified: ${new Date(stats.mtime).toLocaleString()}`);
});
});
});
在這些示例中,我們首先讀取目錄中的每個條目,然后使用相應的系統調用或庫函數來獲取文件的最后修改時間,并將其格式化為可讀的字符串形式。注意,這些示例假設你有足夠的權限來訪問目錄和文件。