2015-12-03 36 views
-1

我試圖在執行我的程序時在用戶在命令行上指定的目錄中搜索文件。它應該查看指定的目錄,並檢查該目錄內的子目錄並遞歸搜索該文件。在目錄中搜索以查看C中是否存在文件

我在這裏有打印語句,試圖分析變量傳遞的方式以及它們如何變化。在我的while循環中,它永遠不會檢查它是否是一個文件,或者只是else語句說它沒有找到。每次都檢查它是否是一個目錄,顯然不是這種情況。

謝謝你的幫助。我對dirent和stat不是很熟悉/很舒服,所以我一直在努力審查並確保在此期間正確使用它們。

#include <unistd.h> 
#include <stdio.h> 
#include <dirent.h> 
#include <string.h> 
#include <sys/stat.h> 
#include <stdlib.h> 
#include <errno.h> 

void traverse(char *dir, char *file) { 

    DIR *directory; 
    struct dirent *structure; 
    struct stat info; 

    printf("Current directory to search through is: %s\n", dir); 
    printf("Current file to search for is: %s\n", file); 
    printf("\n"); 
    printf("\n"); 

    // make sure the directory can be opened 
    if((directory = opendir(dir)) == NULL) { 
     fprintf(stderr, "The directory could not be opened. %s\n", strerror(errno)); 
     return; 
    } 

    chdir(dir); // change to the directory 

    while((structure = readdir(directory)) != NULL) { // loop through it 
     fprintf(stderr, "before the change it is: %s\n", dir); 
     lstat(structure->d_name, &info); // get the name of the next item 

     if(S_ISDIR(info.st_mode)) { // is it a directory? 
      printf("checking if it's a directory\n"); 
      if(strcmp(".", structure->d_name) == 0 || 
       strcmp("..", structure->d_name) == 0) 
       continue; // ignore the . and .. directories 
      dir = structure->d_name; 
      fprintf(stderr, "after the change it is: %s\n", dir); 
      printf("About to recurse...\n"); 
      printf("\n"); 
      traverse(structure->d_name, file); // recursively traverse through that directory as well 
     } 

     else if(S_ISREG(info.st_mode)) { // is it a file? 
      printf("checking if it's a file\n"); 
      if(strcmp(file, structure->d_name) == 0) { // is it what they're searching for? 
       printf("The file was found.\n"); 
      } 
     } 

     else { 
      printf("The file was nout found.\n"); 
     } 
    } 
      closedir(directory); 
} 

int main(int argc, char *argv[]) { 

    // make sure they entered enough arguments 
    if (argc < 3) { 
     fprintf(stderr, "You didn't enter enough arguments on the command line!\n"); 
     return 3; 
    } 

    traverse(argv[2], argv[1]); 

} 
+1

你調用'chdir()'的返回值是多少?如果失敗,您的代碼將無法工作。你還需要檢查'lstat()'的返回值。 –

+0

@AndrewHenle好主意。我加了兩個檢查。 chdir()似乎沒有錯誤。直到大約一半時,lstat()纔會出錯。它通過兩個子目錄循環,然後失敗並將程序的其餘部分擰緊。 – Ryan

+1

你的邏輯錯誤。你'chdir'進入目錄,但永遠不會恢復。第一個目錄後的所有內容都將失敗。 –

回答

0

有這樣一棵樹行走的POSIX函數。它叫做nftw()

它提供了回調機制,它還檢測由構造嚴重的符號鏈接鏈引起的鏈接。

所以我建議你使用它,而不是你這樣做。

像往常一樣man nftw將詳細解釋它的操作。標準的Linux/Unix包含文件是ftw.h.

注意它們是一個稱爲ftw()的函數,現在顯然已經過時了。

0

正如Andrew Medico指出的那樣:chdir下降到目錄但從不回去。因此,只需要插入

chdir(".."); // change back to upper directory 

while循環的結束和traverse()功能的端部之間。

相關問題