Search code examples
c++fstream

C++ windows fstream case sensitive


I'm noticing that on Windows, file opening is case insensitive.

(ex. fstream("text.txt") will open regardless of the actual filename being: Text.txt)

How would I make this case sensitive instead? (The file not opening unless the filename also matches the proper case)


Solution

  • Under Windows the file system API is generally case-insensitive, so the only way is to check the case of the filename yourself. For example,

    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;
    }