
opendir() 函数本身只负责打开目录流,并非直接获取文件属性。要获取目录中文件的属性信息,需要结合 readdir() 和 stat() 等函数。以下示例代码演示如何在类 Unix 系统(如 Linux 和 macOS)中实现:
#include #include #include #include #include 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 函数来实现相同的功能。
笔目鱼英文论文写作器
写高质量英文论文,就用笔目鱼
87 查看详情
以上就是如何用copendir获取目录文件属性的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/535528.html
微信扫一扫
支付宝扫一扫