每日一篇--獲取資料夾下指定字尾的所有檔名
阿新 • • 發佈:2019-02-14
#include <stdlib.h> #include <stdio.h> #include <dirent.h> #define SUFFIX ".txt" #define FILE_NAME_LEN 255 #define SUFFIX_LEN 20 typedef char (*file_name)[FILE_NAME_LEN]; typedef struct specfi_file { int file_count;//檔案總數 char suffix[SUFFIX_LEN];//填充字尾名 file_name *name;//儲存檔名 }spfile; int readSpecficFile(spfile *file,char *basePath) { DIR *dir; struct dirent *ptr; if ((dir=opendir(basePath)) == NULL) { perror("Open dir error..."); exit(1); } memset(file->suffix,'\0',sizeof(file->suffix)); file->file_count = 0; strcpy(file->suffix,SUFFIX); 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) ///file { char * p = strchr(ptr->d_name, '.'); if(p != NULL) { if(!strcmp(p, file->suffix)) { printf("d_name:%s\n",ptr->d_name); file->name[file->file_count] = (file_name )malloc(FILE_NAME_LEN); memset(file->name[file->file_count],'\0',strlen(ptr->d_name)+1); strcpy(file->name[file->file_count],ptr->d_name); file->file_count++; } } } else if(ptr->d_type == 10) ///link file continue; else if(ptr->d_type == 4) ///dir continue; } closedir(dir); return file->file_count; } int main(int argc,char *argv[]) { //generate_url_txt(); //send_request(); spfile sp; readSpecficFile(&sp,"."); for(int i=0;i<sp.file_count;i++) { printf("file[i] = %s\n",sp.name[i]); free(sp.name[i]); } printf("sfsfsdf\n"); return 0; }