How can I calculate the complete buffer size for GetModuleFileName?

后端 未结 8 2060
花落未央
花落未央 2020-12-17 17:08

The GetModuleFileName() takes a buffer and size of buffer as input; however its return value can only tell us how many characters is has copied, and if the size is not enoug

8条回答
  •  无人及你
    2020-12-17 17:51

    Here is a another solution with std::wstring:

    DWORD getCurrentProcessBinaryFile(std::wstring& outPath)
    {
        // @see https://msdn.microsoft.com/en-us/magazine/mt238407.aspx
        DWORD dwError  = 0;
        DWORD dwResult = 0;
        DWORD dwSize   = MAX_PATH;
    
        SetLastError(0);
        while (dwSize <= 32768) {
            outPath.resize(dwSize);
    
            dwResult = GetModuleFileName(0, &outPath[0], dwSize);
            dwError  = GetLastError();
    
            /* if function has failed there is nothing we can do */
            if (0 == dwResult) {
                return dwError;
            }
    
            /* check if buffer was too small and string was truncated */
            if (ERROR_INSUFFICIENT_BUFFER == dwError) {
                dwSize *= 2;
                dwError = 0;
    
                continue;
            }
    
            /* finally we received the result string */
            outPath.resize(dwResult);
    
            return 0;
        }
    
        return ERROR_BUFFER_OVERFLOW;
    }
    

提交回复
热议问题