copendir 函数用于打开一个目录流,以便遍历目录中的文件和子目录
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
DIR *dir = opendir("your_directory_path");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 忽略当前目录(".")和上级目录("..")
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 拼接完整的文件路径
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", "your_directory_path", entry->d_name);
// 获取文件属性
struct stat file_stat;
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);
这个示例将遍历指定目录中的所有文件和子目录,并输出它们的大小、权限和最后修改时间。你可以根据需要修改代码以获取其他文件属性。