如何用copendir获取目录文件属性

如何用copendir获取目录文件属性

opendir() 函数本身只负责打开目录流,并非直接获取文件属性。要获取目录中文件的属性信息,需要结合 readdir() 和 stat() 等函数。以下示例代码演示如何在类 unix 系统(如 linux 和 macos)中实现:

#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_info;     char filepath[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(filepath, sizeof(filepath), "./%s", entry->d_name);          // 获取文件属性         if (stat(filepath, &file_info) == -1) {             perror("stat");             closedir(dir);             return EXIT_FAILURE;         }          // 打印文件属性信息         printf("文件名: %sn", entry->d_name);         printf("文件大小: %lld 字节n", (long long)file_info.st_size);         printf("最后修改时间: %s", ctime(&file_info.st_mtime));         printf("---------------------n");     }      // 关闭目录流     closedir(dir);     return EXIT_SUCCESS; }

这段代码首先打开当前目录,然后循环读取每个目录项。对于每个项,它构建完整的路径,并使用 stat() 函数获取文件属性,包括文件大小和最后修改时间。最后,它打印这些信息。 请注意,此代码仅适用于类 Unix 系统。windows 系统需要使用不同的 API 函数来实现相同的功能。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享