c语言读取一个文件夹下的全部文件(jpg / png 文件)
#include <cstdio> #include <cstring> #include <unistd.h> #include<dirent.h> #include <stdlib.h> // Jinxu void get_files(char *p, char **image_paths, int *img_cnt) { DIR *dir; char base_path[512]; memset(base_path, 0, sizeof base_path); int offset = 0; if(p && p[0] == '.'){ getcwd(base_path, sizeof(base_path)); // get current work director offset ++; } strcat(base_path, p + offset); struct dirent *ptr; if ((dir=opendir(base_path)) == NULL) { printf("Open dir: %s Error...\n", base_path); exit(1); } while ((ptr=readdir(dir)) != NULL) { if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir continue; if(ptr->d_type == 8) ///file (.jpg / .png) { //printf("d_name:%s/%s\n",base_path,ptr->d_name); /// do strings split joint if(strcmp(ptr->d_name + strlen(ptr->d_name) - 3, "jpg") && strcmp(ptr->d_name + strlen(ptr->d_name) - 3, "png")) continue; char *tmp; tmp = (char *)malloc((strlen(base_path) + strlen(ptr -> d_name) + 5) * sizeof (char *)); memset(tmp, 0, sizeof tmp); sprintf(tmp, "%s%c%s", base_path, '/', ptr->d_name); image_paths[(*img_cnt) ++] = tmp; } } closedir(dir); return image_paths; } int main( int argc, char** argv ) { char *image_paths[5005]; int img_cnt = 0; get_files(filename, image_paths, &img_cnt); return 0; }