I have one win32 prog where i want to call GetOpenFileName() but every time it got crash and CommDlgExtendedError() return error code as 1008. Please help me out.
char Filestring[MAX_PATH] = "\0";
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.lpstrFile = (LPWSTR)Filestring;
ofn.nMaxFile = MAX_PATH;
if (GetOpenFileName(&ofn) == TRUE)
{
}
else
{
int err = CommDlgExtendedError();
}
You are using the
TCHARversion of theGetOpenFileName()API, which maps to either the ANSI (GetOpenFileNameA()) or Unicode (GetOpenFileNameW()) API depending on whetherUNICODEis defined.Since
ofn.lpstrFileis accepting aLPWSTR(wchar_t*) pointer, expecting it to point at awchar[]buffer, your project clearly hasUNICODEdefined. But you are giving it a type-casted pointer to achar[]buffer instead, which has 1/2 the storage space than you are telling the API is available for it to write to.Your type-cast on the
ofn.lpstrFilefield is lying to the API. The code is calling the Unicode API, so it will write Unicode data to yourchar[]buffer, giving you mojibake output, and risking a buffer overflow.You should use a
TCHAR[]buffer instead to match what the API is expecting, eg:Otherwise, use the ANSI or Unicode API explicitly, depending on your desired character encoding, eg: