2013-10-06 57 views
1

所以我寫了一個簡短的C程序,探索我的計算機上的文件來查找某個文件。我寫了一個簡單的函數,將一個目錄,打開它的環顧四周:看似隨機opendir()失敗C

int exploreDIR (char stringDIR[], char search[]) 
{  
    DIR* dir; 
    struct dirent* ent; 

    if ((dir = opendir(stringDIR)) == NULL) 
    { 
     printf("Error: could not open directory %s\n", stringDIR); 
     return 0;    
    } 

    while ((ent = readdir(dir)) != NULL) 
    { 
     if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) 
      continue; 

     if (strlen(stringDIR) + 1 + strlen(ent->d_name) > 1024) 
     { 
      perror("\nError: File path is too long!\n"); 
      continue; 
     }  

     char filePath[1024]; 
     strcpy(filePath, stringDIR); 
     strcat(filePath, "/"); 
     strcat(filePath, ent->d_name); 

     if (strcmp(ent->d_name, search) == 0) 
     { 
      printf(" Found it! It's at: %s\n", filePath); 
      return 1; 
     } 

     struct stat st; 
     if (lstat(filePath, &st) < 0) 
     { 
      perror("Error: lstat() failure"); 
      continue; 
     } 

     if (st.st_mode & S_IFDIR) 
     { 
      DIR* tempdir; 
      if ((tempdir = opendir (filePath))) 
      { 
       exploreDIR(filePath, search);    
      } 

     } 

    } 
    closedir(dir); 
    return 0; 
} 

不過,我不斷收到輸出:

Error: could not open directory /Users/Dan/Desktop/Box/Videos 
Error: could not open directory /Users/Dan/Desktop/compilerHome 

的問題是,我不知道它是什麼這些文件可能會導致opendir()失敗。我沒有在任何程序中打開它們。他們只是我在桌面上創建的簡單文件夾。有誰知道這個問題會是什麼?

+0

'chmod r + x/Users/Dan/Desktop/Box/Videos'並重試。 – 2013-10-06 19:12:03

+0

只需通過'sudo'執行 –

+2

檢查'errno'告訴你什麼? – Oswald

回答

2

您打電話給opendir()每個closedir()兩次。也許你用完了資源。

+0

啊,那是問題所在!我不能相信我忘記了第二個opendir()。謝謝。 –