0
我試圖遞歸搜索目錄的文件和輸出文件的目錄,如果它匹配給定:遞歸搜索文件
static int *search(char *path, const char *request, int depth, bool verbose)
{
DIR *dir;
struct dirent *ent;
char *start_dir = strcmp(path, "/") == 0 ? "root" : path;
printf("\nStarting in '%s' directory..\n\n", start_dir);
if ((dir = opendir(path)) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (verbose == true)
{
printf("Searching directory %s for file %s\n", ent->d_name, request);
}
if (ent->d_type == DT_DIR)
{
if ((strlen(path) + strlen(ent->d_name) + 1) > PATH_MAX)
{
puts("Path to long, cannot continue..");
}
else
{
if (ent->d_name == DT_DIR && strcmp(ent->d_name, ".") != 0 &&
strcmp(ent->d_name, "..") != 0)
{
printf("%s\n", ent->d_name);
}
}
}
}
}
return 0;
}
這會工作,但它不會輸出的文件或目錄在目錄裏面。示例:
@ubuntu:~/bin/c/find-files$ ./utilis test/-V
Initialized to search for file: 'test'..
Starting in 'root' directory..
Searching directory vmlinuz.old for file test
Searching directory boot for file test
Searching directory home for file test
Searching directory libx32 for file test
Searching directory lib32 for file test
Searching directory lib64 for file test
Searching directory initrd.img for file test
Searching directory srv for file test
Searching directory usr for file test
Searching directory . for file test
Searching directory cdrom for file test
Searching directory tmp for file test
Searching directory initrd.img.old for file test
Searching directory bin for file test
Searching directory .. for file test
Searching directory proc for file test
Searching directory lib for file test
Searching directory var for file test
Searching directory dev for file test
Searching directory sys for file test
Searching directory media for file test
Searching directory root for file test
Searching directory snap for file test
Searching directory run for file test
Searching directory sbin for file test
Searching directory opt for file test
Searching directory lost+found for file test
Searching directory mnt for file test
Searching directory vmlinuz for file test
Searching directory etc for file test
如何重構此函數以遞歸搜索所有目錄和子目錄中的給定文件名?
你可以做這樣的事情,推目錄堆棧中。如果沒有找到,你可以彈出一個目錄,「cd」,等等,就像實現一個BFS一樣。 – lU5er
「*我如何重構此方法以便遞歸搜索*」何時您將調用算法(或其實現,也許作爲函數)是「遞歸」? – alk
@alk取決於你想告訴我什麼?我也用函數替換了方法,我的不好。 – chx28464