[Linux] C 语言遍历文件夹

[Linux] C 语言遍历文件夹

hanjialeOK

于 2021-04-04 21:13:16 发布

439
收藏 1
分类专栏: C/C++
版权

C/C++
专栏收录该内容
31 篇文章0 订阅
订阅专栏
包含头文件

#include <dirent.h>
1
opendir 用于打开文件夹,readdir 用于获取文件夹中每个文件并用结构体 dirent 存储。

关于文件类型 d_type,常用类型如下

0 # 未知
4 # 目录
8 # 文件
10 # 链接
1
2
3
4
用法如下:

int main(int argc, char* argv[])
{
DIR *dir = NULL;
struct dirent *file;
if((dir = opendir("../images/")) == NULL) {
printf("opendir failed!");
return -1;
}
while(file = readdir(dir)) {
// 判断是否为文件
if (file->d_type != 8) continue;
cout << file->d_name << endl;
// 为文件加上相对路径
char fileName[20] = "../images/";
strcat(fileName, file->d_name);
}
closedir(dir);
return 1;
}
————————————————
版权声明:本文为CSDN博主「hanjialeOK」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43742643/article/details/115433272

posted on 2022-12-06 17:16  zxddesk  阅读(357)  评论(0编辑  收藏  举报

导航