How can I calculate the complete buffer size for GetModuleFileName?

后端 未结 8 2048
花落未央
花落未央 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 18:00

    My example is a concrete implementation of the "if at first you don't succeed, double the length of the buffer" approach. It retrieves the path of the executable that is running, using a string (actually a wstring, since I want to be able to handle Unicode) as the buffer. To determine when it has successfully retrieved the full path, it checks the value returned from GetModuleFileNameW against the value returned by wstring::length(), then uses that value to resize the final string in order to strip the extra null characters. If it fails, it returns an empty string.

    inline std::wstring getPathToExecutableW() 
    {
        static const size_t INITIAL_BUFFER_SIZE = MAX_PATH;
        static const size_t MAX_ITERATIONS = 7;
        std::wstring ret;
        DWORD bufferSize = INITIAL_BUFFER_SIZE;
        for (size_t iterations = 0; iterations < MAX_ITERATIONS; ++iterations)
        {
            ret.resize(bufferSize);
            DWORD charsReturned = GetModuleFileNameW(NULL, &ret[0], bufferSize);
            if (charsReturned < ret.length())
            {
                ret.resize(charsReturned);
                return ret;
            }
            else
            {
                bufferSize *= 2;
            }
        }
        return L"";
    }
    
    0 讨论(0)
  • 2020-12-17 18:01

    Implement some reasonable strategy for growing the buffer like start with MAX_PATH, then make each successive size 1,5 times (or 2 times for less iterations) bigger then the previous one. Iterate until the function succeeds.

    0 讨论(0)
提交回复
热议问题