linux c 讀取目錄及其子目錄下所有.jpg檔案的檔名(無後綴)
阿新 • • 發佈:2019-02-14
此程式用來生成<yolo v2中VOC資料生成labels所需的圖片檔名文件>train.txt
我對其進行了一些小的修改,使得其可以讀取目錄及子目錄中所有.jpg檔案的純檔名,並全部寫入一個train.txt中,程式碼如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <unistd.h> int readFileList(char *basePath,FILE* picname) { DIR *dir; struct dirent *ptr; char base[1000]; int namelen = 0; if ((dir=opendir(basePath)) == NULL) { perror("Open dir error..."); exit(1); } while ((ptr=readdir(dir)) != NULL) { if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir continue; else if(ptr->d_type == 8){namelen = strlen(ptr->d_name);if(ptr->d_name[namelen-4] == '.' && ( ptr->d_name[namelen-3] == 'j' || ptr->d_name[namelen-3] == 'J' ) && ( ptr->d_name[namelen-2] == 'p' || ptr->d_name[namelen-2] == 'P' ) && ( ptr->d_name[namelen-1] == 'g' || ptr->d_name[namelen-1] == 'G' )) ///jpgfile {ptr->d_name[namelen-4] = '\0'; fprintf(picname,"%s\n",ptr->d_name);}} //else if(ptr->d_type == 10) ///link file //printf("d_name:%s/%s\n",basePath,ptr->d_name); else if(ptr->d_type == 4) ///dir { memset(base,'\0',sizeof(base)); strcpy(base,basePath); strcat(base,"/"); strcat(base,ptr->d_name); readFileList(base,picname); } } closedir(dir); return 1; } int main() { FILE* names; DIR *dir; char basePath[1000]; char trainpath[1000]; //pause(); ///get the current absoulte path memset(basePath,'\0',sizeof(basePath)); getcwd(basePath, 999); printf("the current dir is : %s\n",basePath); strcpy(trainpath,basePath); strcat(trainpath,"/VOCdevkit/VOC2007/ImageSets/Main/train.txt"); strcat(basePath,"/VOCdevkit/VOC2007/JPEGImages"); printf("%s\n",basePath); ///get the file list //memset(basePath,'\0',sizeof(basePath)); //strncpy(basePath,"./XL",-1); names = fopen(trainpath,"a+"); readFileList(basePath,names); fclose(names); return 0; }
使用方法:
.
..
creatTrainTxt.out
-VOCdevkit
-Annotations
-ImageSets
-Main
train.txt(this is what you want)
-JPEGImages
-all of pics needed