2009-04-24 21:44

[C語言] 遞迴掃瞄目錄下所有文件(dir_recursive)

opendir , readdir , closedir
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <string.h> 
  4.  
  5. #include <sys/types.h> 
  6. #include <dirent.h> 
  7.  
  8.  
  9. /* dir_recursive [遞迴掃瞄目錄下所有文件] 
  10. * 掃瞄 path 下所有的文件,並輸出至 output 的文件中 
  11. * output 必須為可寫入的文件 
  12. * */ 
  13. int dir_recursive(char *path, FILE *output){ 
  14.    char glue='\\'; // Windows 的分隔符號 
  15.    //char glue='/'; // Linux 的分隔符號 
  16.  
  17.    // 嘗試開啟目錄 
  18.    DIR * dp = opendir(path); 
  19.  
  20.    if (!dp){     
  21.        // 不是目錄,輸出至檔案     
  22.           fprintf(output,"%s\n",path); 
  23.           return 1; 
  24.    } 
  25.  
  26.    struct dirent *filename;     
  27.    while((filename=readdir(dp))){ 
  28.        // 跳過當前及母目錄 
  29.        if(!strcmp(filename->d_name,"..") || !strcmp(filename->d_name,".")){ 
  30.            continue; 
  31.        } 
  32.  
  33.        // 計算新的路徑字串所需的長度 
  34.        int pathLength=strlen(path)+strlen(filename->d_name)+2; 
  35.        // 產生新的陣列空間 
  36.        char *pathStr = (char*)malloc(sizeof(char) * pathLength); 
  37.        // 複製當前目錄路徑至新的陣列空間 
  38.        strcpy(pathStr, path); 
  39.  
  40.        // 檢查目錄分隔符號 
  41.        int i=strlen(pathStr); 
  42.        if(pathStr[i-1]!=glue){ 
  43.            pathStr[i]=glue; 
  44.            pathStr[i+1]='\0'; 
  45.        } 
  46.  
  47.        // 串接次目錄名稱或檔案名稱至新的陣列空間 
  48.        strcat(pathStr, filename->d_name); 
  49.  
  50.        // 遞迴呼叫目錄掃瞄 
  51.        dir_recursive(pathStr,output); 
  52.  
  53.    } 
  54.  
  55.    // 關閉目錄 
  56.    closedir(dp); 
  57.  
  58.    return 1; 
  59. } 
  60.  
  61.  
  62.  
  63. int main(){ 
  64.    // 建立輸出的文件檔 
  65.    FILE *fileOut = fopen("output.txt", "w"); 
  66.  
  67.    // 掃瞄 E:\test 下所有的文件 
  68.    dir_recursive("E:\\test",fileOut);  
  69.  
  70.    return 0; 
  71. } 


參考來源:
[原创]LINUX下用C语言历遍目录 C语言列出目录_小徐博客 学无止境 minix and linux

0 回應: