如何在目录和子目录中递归查找文件

时间:2020-04-14 09:28:24

标签: c find

到目前为止,我已经在Stack Overflow上找到了该文件,但这仅显示程序中给定路径中的文件,而不是用户提供的文件。

我试图将变量添加到printfile函数中,但没有任何效果。

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 printfile(void)
{
    char a,b;
    printf("Path: ");
    gets(a);
    printf("Name: ");
    gets(b);
    char fullpath[MAX_PATH] = { 0 };
    if(findfile_recursive(&a, &b, fullpath)){
        printf("found: %s\n", fullpath);
    }
    else{
        printf("Nothing found");
    }

}

2 个答案:

答案 0 :(得分:1)

char a,b;
printf("Path: ");
gets(a);
printf("Name: ");
gets(b);

gets返回了指向char的指针,但是您使用的是char,还请注意,gets已从标准中删除,您将其替换为{{1 }}并删除该函数留下的尾随换行符。

fgets

答案 1 :(得分:0)

更正后,此代码将发挥作用。

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 printfile(void)
    {
        char name[1024], path[1024];
        printf("\n\nFilename: ");
        scanf("%s",name);
        printf("Path: ");
        scanf("%s",path);
        char fullpath[MAX_PATH] = { 0 };
        if(findfile_recursive(&path,&name, fullpath)){
            printf("Found: %s\n", fullpath);
        }
        else{
            printf("Nothing found\n");
        }
    }
相关问题