Samuel
Samuel

Reputation: 6490

Why is OPENFILENAME lpstrFileTitle param a LPSTR and not LPCSTR?

I am creating some file open dialog and stumbled across something inconsistent in the WinAPI (hehe).

I fully understand why lpstrFile is a LPSTR as the path is written into this variable.

Fine, but why is lpstrFileTitle not LPCSTR? I've read the docs at MSDN and googled around and found no satisfying explanation as it doesn't look like it is modified in any way.

Is this a compatibility remnant or something?

Causes annoying workarounds when passing a std::string as I cannot use c_str() and resort to &str[0].

Upvotes: 3

Views: 1176

Answers (2)

truefish
truefish

Reputation: 151

Related side-note: You must set lpstrFileTitle to a valid buffer for non-Unicode builds.

The docs for OPENFILENAME state that field is ignored if the pointer is null. However, since at least VS2008 the MFC CFileDialog code has included this code:

VC\atlmfc\src\mfc\dlgfile.cpp
void CFileDialog::UpdateOFNFromShellDialog()
{
...
#ifdef UNICODE
...
#else
    ::WideCharToMultiByte(CP_ACP, 0, wcPathName + offset,-1, m_ofn.lpstrFileTitle, m_ofn.nMaxFileTitle, NULL, NULL);
    m_ofn.lpstrFileTitle[m_ofn.nMaxFileTitle - 1] = _T('\0');
#endif
...

The Unicode support correctly handles a NULL lpstrFileTitle and the WideCharToMultiByte basically does nothing. However, the added code to safely terminate the buffer does not check for a null pointer or a nMaxFileTitle==0. The result is an access violation.

Better of course to kill multibyte apps, but if you must compile that way, you have to supply that buffer.

Upvotes: 2

Marius Bancila
Marius Bancila

Reputation: 16338

lpstrFileTitle is also an output buffer. It contains the name and extension without path information of the selected file.

Upvotes: 8

Related Questions