使用FindFirstFile api的Windows 10 C通配符目录搜索失败

问题描述

这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <windows.h>
void filesearch(char* path,char* fname);


int main()
{
    filesearch("C:\\Users\\Admin Local\\Documents","test.txt");
    int choice;
    char folder[80],fname[80];
    printf("\nWhich directory will I search in?    ");
    gets(folder);
    printf("\nWhat is the filename of the required file?     ");
    gets(fname);
    filesearch(folder,fname);
}

void filesearch(char* folder,char* fname){
    char path[80];
    HANDLE filehandle;
    WIN32_FIND_DATA ffd;


    strcpy(path,folder);
    strcat(path,"\\*");
   // printf("%s\n",path);

    filehandle=FindFirstFile(path,&ffd);

    do{
        if(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
            if(strcmp(ffd.cFileName,".")==0){
                FindNextFile(filehandle,&ffd);
                continue;
            }
            char subpath[80];
            strcpy(subpath,folder);
            strcat(subpath,"\\");
            strcat(subpath,ffd.cFileName);
            filesearch(subpath,fname);
            continue;
        }
        if(strcmp(ffd.cFileName,fname)==0)
            printf("\n%s\\%s\n",folder,ffd.cFileName);
    }while(FindNextFile(filehandle,&ffd)!=0);
    FindClose(filehandle);
    return;
}

当我放置一个目录时: C:\ Users \ Admin Local \ Documents和通配符* .txt 没发生什么事。 该程序突然停止,并且窗口显示错误退出

但是我放的时候: C:\ Users \ Admin Local \ Documents和文件名test.txt 它会按原样输出

我在第10行对该函数进行了一次测试调用,以便我可以检查它是否正常运行,而不必担心用户输入和输入处理错误

测试电话工作正常。

代码中是否有任何问题,或者这是一个防病毒问题,最重要的是,我该如何解决

解决方法

第一个问题是,所有80个字符的缓冲区对于安全搜索而言都太小了。应该至少用char folder[_MAX_PATH]和类似的字符替换它们。那么主要问题如下:

    if(strcmp(ffd.cFileName,fname)==0)
        printf("\n%s\\%s\n",folder,ffd.cFileName);

这会将文件名与通配符进行比较,并且对于真正的通配符将失败。它应该是:

    if(PathMatchSpec(ffd.cFileName,fname))
        /* ... */

使用PathMatchSpec需要#include <shlwapi.h>并链接到shlwapi.lib