STL string question

Started by
3 comments, last by Zahlman 16 years, 9 months ago
Hiya, I need to store the character array returned from GetModuleFileName() in a string. Is it possible to do this:

std::wstring strAppPath;
GetModuleFileName( NULL, strAppPath.c_str(), MAX_PATH );
Or do I need to have it returned to a wide character array, like this:

wchar_t chAppPath[MAX_PATH + 1];
ZeroMemory( chAppPath, sizeof( chAppPath ) );
GetModuleFileName( NULL, chAppPath, MAX_PATH );

std::wstring strAppPath( chAppPath );
Thanks for any help [smile] James.
Advertisement
You have to use the second method; the pointer returned by c_str() is const.
So it is, thanks.
Do you need the zero memory op?
I dont imagine so, but defensive coding never hurt aye [smile]
MSDN says:

Quote:lpFilename
[out] A pointer to a buffer that receives the fully-qualified path of the module. If the length of the path exceeds the size that the nSize parameter specifies, the function succeeds, and the string is truncated to nSize characters and cannot be null terminated.


So, if the name is any shorter, it will certainly null-terminate stuff, so you don't need to zero out the array... but you might want to drop a null byte into the last slot ;)

Except that there's a cleaner way to do it:

Quote:If the function succeeds, the return value is the length of the string that is copied to the buffer, in TCHARs. If the buffer is too small to hold the module name, the string is truncated to nSize, the function returns nSize, and the function sets the last error to ERROR_INSUFFICIENT_BUFFER.

If the function fails, the return value is 0 (zero).


So, whether the return is 0 or not, it indicates a valid number of characters to copy out of the buffer. We can just leave it uninitialized, and instead of using the "initialize from a C-string" constructor of std::wstring, we use the "initialize from a range of characters" one.

And once you have this set up, of course, you'll want to wrap it up in a function with a more meaningful name, and set it up so that it uses the appropriate types according to the unicode setting:

typedef std::basic_string<TCHAR> tstring;tstring getProgramName() {  // Don't need a +1, because we won't get a null terminator if the buffer is  // filled, and we don't need to add one in that case either.  TCHAR buffer[MAX_PATH];  int len = GetModuleFileName(NULL, buffer, MAX_PATH);  // Behold, the range constructor for the string:  return tstring(buffer, buffer + len);  // If there was an error for some reason, we return an empty string.}

This topic is closed to new replies.

Advertisement