所以我有一個程序,並通過文件名,我需要找到/打開所有存在於當前目錄和所有子目錄名稱的文件。如何在C中的目錄/子目錄中找到文件的實例?
我不知道子目錄的名稱。我不關心他們的名字或任何其他文件,我只需要能夠用傳入的名字打開所有文件。
謝謝!
所以我有一個程序,並通過文件名,我需要找到/打開所有存在於當前目錄和所有子目錄名稱的文件。如何在C中的目錄/子目錄中找到文件的實例?
我不知道子目錄的名稱。我不關心他們的名字或任何其他文件,我只需要能夠用傳入的名字打開所有文件。
謝謝!
以下是ntfw()
的示例。
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf){
char *fileName = "findMe.txt";
/* fpath holds the full path of the file from the specified starting directory */
if (strstr(fpath, fileName)){
printf("Match found!\n");
}
return 0;
}
int main(int argc, char **argv){
/* If a starting directory isn't specified, use the current dir */
if (nftw((argc < 2) ? "." : argv[1], display_info, 20, 0) == -1) {
perror("nftw");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
當然,你會驗證'strstr()'的返回值,以確保你沒有處理_ifindMe.txt_或_dont_findMe.txt_。 :-) –
@ChronoKitsune錯誤檢查確實很重要! ......並且在我的大部分答案中都沒有提到:S – Chirality
這僅僅是一條評論,告訴OP,所提供的代碼僅僅是一個演示如何使用'nftw()'來實現一個更簡單的目標,而不是批評。 :-) –
對於Linux和其他大多數系統上,你想使用['nftw()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nftw.html)。您可以使用'fn'參數來引用一個函數,如果該名稱與您的文件名匹配,則對該文件進行操作。 –
如果您想通過遍歷目錄('opendir','readdir','closedir')並解析鏈接的元數據('stat')。 –