在C++中,可以使用glob函數(shù)來進行遞歸搜索文件或目錄。glob函數(shù)可以匹配指定模式的文件或目錄,并返回一個包含匹配結果的字符串數(shù)組。
以下是一個簡單的例子,演示如何在C++中使用glob函數(shù)進行遞歸搜索:
#include <iostream>
#include <glob.h>
void searchFiles(const std::string& pattern) {
glob_t glob_result;
glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
for(size_t i = 0; i < glob_result.gl_pathc; ++i){
std::cout << glob_result.gl_pathv[i] << std::endl;
}
for(size_t i = 0; i < glob_result.gl_pathc; ++i){
if(glob_result.gl_pathv[i][strlen(glob_result.gl_pathv[i]) - 1] == '/'){
searchFiles(std::string(glob_result.gl_pathv[i]) + "*");
}
}
globfree(&glob_result);
}
int main() {
searchFiles("path/to/search/*");
return 0;
}
在上面的代碼中,我們定義了一個名為searchFiles的函數(shù),它接受一個文件或目錄的匹配模式作為參數(shù)。在函數(shù)內部,我們使用glob函數(shù)來搜索匹配指定模式的文件或目錄,并將結果打印出來。然后我們遞歸搜索每個子目錄,直到找到所有匹配的文件或目錄為止。
通過使用glob函數(shù),我們可以方便地進行遞歸搜索文件或目錄,并找到符合特定條件的文件或目錄。