在 Debian 系统中,你可以使用 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");
closedir(dir);
return EXIT_FAILURE;
}
// 输出文件名和大小
printf("Name: %s\n", entry->d_name);
printf("Size: %ld bytes\n", file_stat.st_size);
// 你可以根据需要输出更多属性,例如:
printf("Type: %s\n", S_ISREG(file_stat.st_mode) ? "Regular file" : "Directory");
printf("Last modified: %s", ctime(&file_stat.st_mtime));
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
opendir 打开当前目录(.)。readdir 遍历目录中的每个条目。stat 函数获取文件的详细信息,并存储在 struct stat 结构体中。stat 调用失败。closedir 关闭目录以释放资源。