如何用copendir獲取目錄文件屬性

如何用copendir獲取目錄文件屬性

opendir() 函數本身只負責打開目錄流,并非直接獲取文件屬性。要獲取目錄中文件的屬性信息,需要結合 readdir() 和 stat() 等函數。以下示例代碼演示如何在類 unix 系統(如 linux 和 macos)中實現:

#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <string.h>  int main() {     DIR *dir;     struct dirent *entry;     struct stat file_info;     char filepath[1024];      // 打開當前目錄     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;          // 構造完整文件路徑         snprintf(filepath, sizeof(filepath), "./%s", entry->d_name);          // 獲取文件屬性         if (stat(filepath, &file_info) == -1) {             perror("stat");             closedir(dir);             return EXIT_FAILURE;         }          // 打印文件屬性信息         printf("文件名: %sn", entry->d_name);         printf("文件大小: %lld 字節n", (long long)file_info.st_size);         printf("最后修改時間: %s", ctime(&file_info.st_mtime));         printf("---------------------n");     }      // 關閉目錄流     closedir(dir);     return EXIT_SUCCESS; }

這段代碼首先打開當前目錄,然后循環讀取每個目錄項。對于每個項,它構建完整的路徑,并使用 stat() 函數獲取文件屬性,包括文件大小和最后修改時間。最后,它打印這些信息。 請注意,此代碼僅適用于類 Unix 系統。windows 系統需要使用不同的 API 函數來實現相同的功能。

? 版權聲明
THE END
喜歡就支持一下吧
點贊5 分享