copendir
函數本身并不直接讀取文件屬性,而是用于打開一個目錄流,以便后續使用其他函數(如 readdir
)來讀取目錄中的文件和子目錄。如果你想要獲取目錄中文件的屬性,你需要在成功打開目錄流之后,使用 readdir
函數讀取目錄項,并結合 stat
或 lstat
函數來獲取每個文件或目錄的屬性。
以下是一個簡單的示例,展示了如何使用 copendir
、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;
char path[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(path, sizeof(path), "./%s", entry->d_name);
// 獲取文件屬性
if (stat(path, &file_stat) == -1) {
perror("stat");
closedir(dir);
return EXIT_FAILURE;
}
// 打印文件屬性
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;
}
在這個示例中,我們首先使用 opendir
函數打開當前目錄(.
)。然后,我們使用 readdir
函數循環讀取目錄中的每個條目。對于每個條目,我們構建文件的完整路徑,并使用 stat
函數獲取文件的屬性。最后,我們打印出文件的大小、權限和最后修改時間等信息。
請注意,這個示例僅用于演示目的,實際使用時可能需要根據具體需求進行調整。