在Linux中,readdir
函數用于讀取目錄中的條目。但是,readdir
本身并不直接提供文件的屬性信息。要獲取文件屬性信息,你需要使用其他函數,如stat
、lstat
或fstat
。
以下是一個簡單的示例,展示了如何使用opendir
、readdir
和stat
函數來獲取目錄中文件的屬性信息:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.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;
}
// 使用stat函數獲取文件屬性信息
if (stat(entry->d_name, &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("Last modified: %s", ctime(&file_stat.st_mtime));
}
closedir(dir);
return EXIT_SUCCESS;
}
這個示例程序首先打開當前目錄,然后使用readdir
函數讀取目錄中的每個條目。對于每個條目,它使用stat
函數獲取文件的屬性信息,并輸出文件名、大小和最后修改時間。注意,這個示例僅適用于UNIX-like系統,如Linux。