alt=”linux readdir如何實(shí)現(xiàn)文件屬性獲取” />
在Linux系統(tǒng)中,readdir函數(shù)被用來讀取目錄里的文件及子目錄信息。若想獲取文件屬性,則需配合stat函數(shù)共同完成。下面是一個(gè)簡(jiǎn)單的代碼示例,展示如何利用readdir與stat函數(shù)來取得目錄內(nèi)文件的屬性:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.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) { // 跳過當(dāng)前目錄和上級(jí)目錄的特殊條目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 組合完整的文件路徑 char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name); // 獲取文件屬性 if (stat(path, &file_stat) == -1) { perror("stat"); continue; } // 顯示文件屬性 printf("File: %sn", entry->d_name); printf("Size: %ld bytesn", file_stat.st_size); printf("Last modified: %s", ctime(&file_stat.st_mtime)); } closedir(dir); return EXIT_SUCCESS; }
這段程序接收一個(gè)目錄路徑作為命令行參數(shù),接著利用readdir函數(shù)逐一讀取目錄內(nèi)的所有條目。對(duì)于每一個(gè)條目,我們用stat函數(shù)來獲取其屬性,并且顯示文件大小以及最后的修改日期。同時(shí),我們忽略了代表當(dāng)前目錄的“.”和上一級(jí)目錄的“..”這兩個(gè)特殊條目。
當(dāng)你編譯并執(zhí)行此程序時(shí),將會(huì)得到類似于以下的結(jié)果:
File: example.txt Size: 1234 bytes Last modified: Thu Oct 15 14:23:12 2020 File: log.txt Size: 5678 bytes Last modified: Wed Oct 16 10:45:34 2020
本例僅演示了如何獲取文件大小和最后的修改時(shí)間,實(shí)際上file_stat結(jié)構(gòu)體中還有許多其他的成員可以用來獲取更多的文件屬性。