Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C递归搜索文件夹和子文件夹中的文件_C_Windows - Fatal编程技术网

C递归搜索文件夹和子文件夹中的文件

C递归搜索文件夹和子文件夹中的文件,c,windows,C,Windows,我的程序从用户那里获取输入路径,并从.csv文件中查找名称与列对应的文件,其中oldpath是用户输入路径,然后在while循环中使用get_-between_分隔符从.csv中每行的第一个单元格中获取我要查找的文件名 我不明白的是,如果该文件不存在于基本目录中或不存在,我如何检查该文件的所有子目录,同时保持程序的功能 strcpy(oldnp, oldpath); strcat(oldnp, "/"); strcat(oldnp, get_between_delimiter(com

我的程序从用户那里获取输入路径,并从.csv文件中查找名称与列对应的文件,其中oldpath是用户输入路径,然后在while循环中使用get_-between_分隔符从.csv中每行的第一个单元格中获取我要查找的文件名

我不明白的是,如果该文件不存在于基本目录中或不存在,我如何检查该文件的所有子目录,同时保持程序的功能

  strcpy(oldnp, oldpath);
  strcat(oldnp, "/");
  strcat(oldnp, get_between_delimiter(commande[cnt] , 0));
  strcat(oldnp, ".png");
  source = fopen(oldnp, "r");
  if ((source = fopen(oldnp, "r")) == NULL)
   file_found();
  else
   ;?
用于列出目录中的所有文件,然后与每个文件进行比较。或者执行递归搜索并搜索每个子目录

您还可以调整通配符

此示例在c:\\test上查找something.png,如果找不到,将在c:\\test的子目录中查找

确保不要在C:\上执行递归搜索,因为这将遍历驱动器上的所有文件

#include <stdio.h>
#include <Windows.h>

int findfile_recursive(const char *folder, const char *filename, char *fullpath)
{
    char wildcard[MAX_PATH];
    sprintf(wildcard, "%s\\*", folder);
    WIN32_FIND_DATA fd;
    HANDLE handle = FindFirstFile(wildcard, &fd);
    if(handle == INVALID_HANDLE_VALUE) return 0;
    do  
    {
        if(strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) 
            continue;
        char path[MAX_PATH];
        sprintf(path, "%s\\%s", folder, fd.cFileName);

        if(_stricmp(fd.cFileName, filename) == 0) 
            strcpy(fullpath, path);
        else if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            findfile_recursive(path, filename, fullpath);
        if(strlen(fullpath))
            break;
    } while(FindNextFile(handle, &fd));
    FindClose(handle);
    return strlen(fullpath);
}

int main(void)
{
    char fullpath[MAX_PATH] = { 0 };
    if(findfile_recursive("c:\\test", "something.png", fullpath))
        printf("found: %s\n", fullpath);
    return 0;
}

非常感谢,似乎正在工作,正在努力实现它。