使用C语言的 opendir、readdir 函数读取遍历指定目录下的指定类型的文件。
指定目录结构:
指定 bmp 或 jpg 格式文件:
实现代码:
bool search_file(const char* src_dir, const char* file_type)
{
struct dirent * entry;
//1,打开目录操作
DIR* dirp = opendir(src_dir);
//3,读取目录操作
char src_buf[1024] = {0};
while (1) {
entry = readdir(dirp);
if (entry == NULL) {
break;
}
//比对字符串,排除.和..
if (!strncmp(entry->d_name, ".", 1) || !strncmp(entry->d_name, "..", 2)) {
continue;
}
//拼接路径+文件名
sprintf(src_buf, "%s/%s", src_dir, entry->d_name);
if (entry->d_type == DT_DIR) {
//封装函数,递归创建目录
search_file(src_buf, file_type);
}if (entry->d_type == DT_REG) {
char * pExt;
pExt = strrchr(src_buf, '.');
if ( strcmp(pExt, file_type) == 0 )//查找指定类型“file_type”的文件
{
printf("file : %s\n", src_buf);
}
}
}
return true;
}