2016-05-15 26 views
-2

我需要找到一種方法來掃描文件夾 - (例如-C:\ Users \ User \ Documents \ HW),並檢查是否有一些文本我從用戶那裏得到。我需要返回哪些文件具有完全相同的文本。我以前從未使用過dirent.h,我不知道如何使用它。如何掃描一個文件夾中的文本使用dirent頭在C

+1

想法是在目錄路徑上使用'opendir',然後用'readdir'循環查找所有文件,並且對於每個文件,您可能還必須「打開」,「讀取」和「關閉」。你也可以爲每個文件使用'fopen','fread'和'fclose'。一旦完成,你還應該調用'closedir'。 –

+0

在向全世界尋求幫助之前,請自己做一些研究。謝謝。 – alk

+0

謝謝Henrik!並猜測我嘗試了什麼,烷。並失敗。那麼「向世界求助」有什麼不對?這是一個問題和答案的網站! –

回答

0

你定義自己的error函數處理錯誤:

// Standard error function 
void fatal_error(const char* message) { 

    perror(message); 
    exit(1); 
} 

導線功能基本統計當前文件,如果該文件是目錄,我們將進入該目錄。在目錄本身中非常重要的是檢查當前目錄是否是。或..因爲這可能導致不定式循環。

void traverse(const char *pathName){ 

    /* Fetching file info */ 
    struct stat buffer; 
    if(stat(pathName, &buffer) == -1) 
    fatalError("Stat error\n"); 

    /* Check if current file is regular, if it is regular, this is where you 
    will see if your files are identical. Figure out way to do this! I'm 
    leaving this part for you. 
    */ 

    /* However, If it is directory */ 
    if((buffer.st_mode & S_IFMT) == S_IFDIR){ 

    /* We are opening directory */ 
    DIR *directory = opendir(pathName); 
    if(directory == NULL) 
     fatalError("Opening directory error\n"); 

    /* Reading every entry from directory */ 
    struct dirent *entry; 
    char *newPath = NULL; 
    while((entry = readdir(directory)) != NULL){ 

     /* If file name is not . or .. */ 
     if(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")){ 

     /* Reallocating space for new path */ 
     char *tmp = realloc(newPath, strlen(pathName) + strlen(entry->d_name) + 2); 
     if(tmp == NULL) 
      fatalError("Realloc error\n"); 
     newPath = tmp; 

     /* Creating new path as: old_path/file_name */ 
     strcpy(newPath, pathName); 
     strcat(newPath, "/"); 
     strcat(newPath, entry->d_name); 

     /* Recursive function call */ 
     traverse(newPath); 
     } 
    } 
    /* Since we always reallocate space, this is one memory location, so we free that memory*/ 
    free(newPath); 

    if(closedir(directory) == -1) 
     fatalError("Closing directory error\n"); 
    } 

} 

你也可以做到這一點使用chdir()功能,它也許更容易這樣,但我想告訴你這種方法,因爲它是非常ilustrating。但是最簡單的遍歷低谷文件夾/文件層次結構的方法是NFTW函數。確保你在man頁面檢查。

如果您還有其他問題,請隨時詢問。

+0

非常感謝你Aleksandar !!! –