在C語言中,使用readdir
函數可以讀取目錄中的文件和子目錄。但是,readdir
本身并不直接提供文件的屬性信息。要獲取文件的屬性,你需要結合其他函數,如stat
。
以下是一個簡單的示例,展示了如何使用readdir
和stat
來獲取目錄中文件的屬性:
#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_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);
// 獲取文件的屬性
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 輸出文件名和屬性
printf("File: %s\n", entry->d_name);
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Permissions: %o\n", file_stat.st_mode);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
// 關閉目錄
closedir(dir);
return EXIT_SUCCESS;
}
這個示例程序首先打開當前目錄(.
),然后使用readdir
讀取目錄中的每個條目。對于每個條目,它跳過當前目錄和上級目錄,然后構建文件的完整路徑。接下來,它使用stat
函數獲取文件的屬性,并輸出文件名、大小、權限和最后修改時間。
注意:在實際應用中,你可能需要根據實際需求對代碼進行調整。例如,你可能需要處理符號鏈接、錯誤處理等。