页面加载中,请稍候
来源:嵌入式大杂烩发布时间:2022-01-27945浏览
询问 AI项目开发过程中经常需要读取目录下所有文件,故总结此递归读取文件夹下所有文件的示例程序以作备忘。
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int read_dir_r(char *path)
{
DIR *dp = NULL;
struct dirent *st;
struct stat sta;
int ret = 0;
char tmp_name[1024]={0};
dp = opendir(path);
if(dp == NULL)
{
printf(open dir error!!\n");
return -1;
}
while(1)
{
st = readdir(dp);
if(NULL == st) 读取完毕
{
break;
}
strcpy(tmp_name, path);
if(path[strlen(path)-1] != '/') 判断路径名是否带/
strcat(tmp_name,);
strcat(tmp_name,st->d_name); 新文件路径名
ret = stat(tmp_name, &sta); 查看目录下文件属性
if(ret < 0)
{
printf(read stat fail\n");
return -1;
}
if(S_ISDIR(sta.st_mode)) 如果为目录文件
{
if( 0 == strcmp(..",st->d_name) || 0 == strcmp(.",st->d_name)) 忽略当前目录和上一层目录
continue;
else
{
read_dir_r(tmp_name); 递归读取
}
}
else 不为目录则打印文件路径名
{
printf(%s\n",tmp_name);
}
}
closedir(dp);
return 0;
}
int main(int argc,char *argv[])
{
read_dir_r(./test"); 打印当前test目录下所有的文件路径
return 0;
}
创建几个文件夹及文件以作测试,结构如下所示:

程序执行结果:成功的打印出五个文件路径名。
原文链接:https://xiaoyege.blog.csdn.net/article/details/86683284往期推荐:
在公众号聊天界面回复1024,可获取嵌入式资源;回复 m ,可查看文章汇总。
新闻来源:嵌入式大杂烩,文中所述为作者独立观点,不代表icspec立场。更多精彩资讯请下载icspec App。如对本稿件有异议,请联系微信客服specltkj。
暂无评论哦,快来评论一下吧!

2026-07-13
2026-06-24

2026-06-10