在c語(yǔ)言中,你可以使用readdir函數(shù)來(lái)讀取目錄中的文件和子目錄。但是,readdir本身并不直接提供文件的修改時(shí)間。要獲取文件的修改時(shí)間,你需要使用stat函數(shù)。
以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用readdir和stat來(lái)獲取目錄中文件的修改時(shí)間:
#<span>include <stdio.h></span> #<span>include <stdlib.h></span> #<span>include <dirent.h></span> #<span>include <sys/stat.h></span> #<span>include <time.h></span> int main() { DIR *dir; <span>struct dirent *entry;</span> <span>struct stat file_stat;</span> // 打開(kāi)目錄 dir = opendir("."); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } // 讀取目錄中的條目 while ((entry = readdir(dir)) != NULL) { // 跳過(guò)當(dāng)前目錄和上級(jí)目錄的特殊條目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 構(gòu)建文件的完整路徑 char path[PATH_MAX]; snprintf(path, sizeof(path), "./%s", entry->d_name); // 獲取文件的狀態(tài)信息 if (stat(path, &file_stat) == -1) { perror("stat"); continue; } // 打印文件名和修改時(shí)間 char time_buf[26]; ctime_r(&file_stat.st_mtime, time_buf); time_buf[strcspn(time_buf, " ")] = 0; // 去掉換行符 printf("%s - Modified: %s", entry->d_name, time_buf); } // 關(guān)閉目錄 closedir(dir); return EXIT_SUCCESS; }
這個(gè)程序首先打開(kāi)當(dāng)前目錄(.),然后使用readdir讀取目錄中的每個(gè)條目。對(duì)于每個(gè)條目,它使用stat函數(shù)獲取文件的狀態(tài)信息,包括修改時(shí)間。然后,它使用ctime_r函數(shù)將修改時(shí)間轉(zhuǎn)換為可讀的字符串格式,并打印出來(lái)。
注意:ctime_r是線程安全的版本,如果你在一個(gè)多線程程序中使用,應(yīng)該使用這個(gè)版本而不是ctime。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END