8、讀取資料夾下的檔名
阿新 • • 發佈:2019-01-05
題意:處理指定路徑下,資料夾的檔案;
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> char filename[256][256]; int len = 0; int trave_dir(char* path, int depth) { DIR *d; //宣告一個控制代碼 struct dirent *file; //readdir函式的返回值就存放在這個結構體中 struct stat sb; if(!(d = opendir(path))) { printf("error opendir %s!!!/n",path); return -1; } while((file = readdir(d)) != NULL) { //把當前目錄.,上一級目錄..及隱藏檔案都去掉,避免死迴圈遍歷目錄 if(strncmp(file->d_name, ".", 1) == 0) continue; strcpy(filename[len++], file->d_name); //儲存遍歷到的檔名 //判斷該檔案是否是目錄,及是否已搜尋了三層,搜尋了三層目錄 if(stat(file->d_name, &sb) >= 0 && S_ISDIR(sb.st_mode) && depth <= 3) { trave_dir(file->d_name, depth + 1); } } closedir(d); return 0; } int main() { int depth = 1; int i; trave_dir("./", depth); for(i = 0; i < len; i++) { printf("%s\t", filename[i]); } printf("\n"); return 0; }