alt=”linux readdir如何實現文件屬性獲取” />
在linux系統中,readdir函數被用來讀取目錄里的文件及子目錄信息。若想獲取文件屬性,則需配合stat函數共同完成。下面是一個簡單的代碼示例,展示如何利用readdir與stat函數來取得目錄內文件的屬性:
#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) { // 跳過當前目錄和上級目錄的特殊條目 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; }
這段程序接收一個目錄路徑作為命令行參數,接著利用readdir函數逐一讀取目錄內的所有條目。對于每一個條目,我們用stat函數來獲取其屬性,并且顯示文件大小以及最后的修改日期。同時,我們忽略了代表當前目錄的“.”和上一級目錄的“..”這兩個特殊條目。
當你編譯并執行此程序時,將會得到類似于以下的結果:
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
本例僅演示了如何獲取文件大小和最后的修改時間,實際上file_stat結構體中還有許多其他的成員可以用來獲取更多的文件屬性。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END