C++ windows fstream 区分大小写

C++ windows fstream case sensitive

我注意到在 Windows 上,文件打开不区分大小写。

(例如 fstream("text.txt") 将打开,无论实际文件名是:Text.txt

我该如何改为区分大小写? (除非文件名也匹配正确的大小写,否则文件不会打开)

Windows下的文件系统API一般是不区分大小写的,所以唯一的办法就是自己检查文件名的大小写。例如,

bool open_stream_ci(const char* pszName, std::fstream& out)
{
    WIN32_FIND_DATAA wfd;
    HANDLE hFind = ::FindFirstFileA(pszName, &wfd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        ::FindClose(hFind);
        if (!strcmp(wfd.cFileName, ::PathFindFileNameA(pszName)))
        {
            out.open(pszName);
            return true;
        }
    }
    return false;
}