FindFirstFileW通配符匹配

时间:2019-04-12 13:15:06

标签: c++ windows winapi

考虑一个独立的示例,其中我使用通配符查询目录中的所有名称:

#include <Windows.h>
#include <fstream>

void add_file(const std::string &path)
{
    std::ofstream  ofs(path,std::ofstream::out);
    ofs.close();
}

void foo(const std::wstring& szDir)
{
    std::cout << "f1 : FindFirstFileW\n";
    WIN32_FIND_DATAW ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    hFind = FindFirstFileW(szDir.c_str(), &ffd);

    if (INVALID_HANDLE_VALUE == hFind) 
    {
        std::cout << "Error in FindFirstFileW : " << GetLastError() << std::endl;
        return;
    } 

    // List all the files in the directory with some info about them.

    do
    {
        std::wcout <<"Long file name " << "  " <<  ffd.cFileName << std::endl;
        std::wcout <<"Short file name " << "  " <<  ffd.cAlternateFileName << std::endl;
    }
    while (FindNextFileW(hFind, &ffd) != 0);

    FindClose(hFind);
}

int main()
{
    const char  odd_filename[] = {static_cast<char>(0xC4U), '.', 't', 'x', 't', 0};

    add_file("C:\\mydir1\\777.Txt");
    add_file(std::string("C:\\mydir1\\") + std::string(odd_filename));

    foo(L"C:\\mydir1\\7*");

    return 0;
}

这给了我如下输出

f1 : FindFirstFileW
Long file name   777.Txt
Short file name
Long file name   ─.txt
Short file name   7F7E~1.TXT

为什么FindFirstFileW会将第二个文件名Ä.txt作为匹配项返回?

1 个答案:

答案 0 :(得分:5)

通配符匹配应用于长文件名和短文件名。第二个文件的简称为7F7E~1.TXT,因此与7*匹配。

documentation的内容如下:

  

以下列表标识了其他一些搜索特征:

     
      
  • 搜索仅在文件名上执行,而不是在日期或文件类型等任何属性上执行(有关其他选项,请参见   FindFirstFileEx
  •   
  • 搜索包括长文件名和短文件名。
  •   
  • 尝试打开带有反斜杠的搜索始终会失败。
  •   
  • lpFileName 参数传递无效的字符串, NULL 或空字符串不是此函数的有效用法。在这种情况下的结果   未定义。
  •   

第二个要点是相关的。

相关问题