在 Linux 下,opendir()
函数用于打开一个目录流,而不是直接获取文件属性。要获取目录中的文件属性,你需要结合使用 readdir()
函数读取目录项,并使用 stat()
函数获取每个文件或目录的属性。
以下是一个简单的示例,展示了如何在 Linux 下使用 opendir()
、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");
continue;
}
// 输出文件属性
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()
函数获取文件属性,并将文件名、大小和最后修改时间输出到控制台。
注意:在实际应用中,你可能需要根据需求对示例代码进行修改,例如处理符号链接、过滤特定类型的文件等。