Microsoft KB Archive/222003

{|
 * width="100%"|

PRB: GetOpenFileName Fails If lpstrFile Buffer Is Not NULL Terminated

 * }

Q222003

-

The information in this article applies to:


 * Microsoft Win32 Application Programming Interface (API), included with:
 * Microsoft Windows NT Server version 4.0
 * Microsoft Windows NT Workstation version 4.0
 * the operating system: Microsoft Windows 2000

-

SYMPTOMS
The GetOpenFileName function fails with a CommDlgExtendedError of CDERR_INITIALIZATION(0x0002).

CAUSE
The lpstrFile buffer of the OPENFILENAME structure is not NULL terminated.

RESOLUTION
According to the Platform SDK documentation, the first character of the lpstrFile buffer must be NULL if the buffer is not being used for initialization of the File Name edit box.

STATUS
This behavior is by design.

MORE INFORMATION
The following Win32 Application demonstrates the problem:

#include 

// If the next line is commented out, GetOpenFileName fails. //#define NULL_TERMINATE

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,                            LPSTR szCmdLine, int nCmdShow) {  long lErrMsg = 0; OPENFILENAME ofn; TCHAR sfile[MAX_PATH];

ZeroMemory(&ofn, sizeof(ofn));

ZeroMemory(sfile, sizeof(TCHAR)*MAX_PATH);

#ifndef NULL_TERMINATE // Not NULL terminated. {  int i;   for (i = 0; i < MAX_PATH; i++) sfile[i] = ' '; }  #else // NULL terminated. sfile[0] = '\0'; #endif

// Initialize OPENFILENAME structure. ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = sfile; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = NULL; ofn.nFilterIndex = 1; ofn.lpstrTitle = TEXT("Please Select a File"); ofn.lpstrInitialDir = NULL; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = NULL; ofn.lCustData = 0; ofn.lpfnHook = 0; ofn.lpTemplateName = 0; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;

// Call GetOpenFileName. if (GetOpenFileName(&ofn)) {      MessageBox(NULL, TEXT("GetOpenFileName Successful"), TEXT("OpenDialog"), MB_OK); }  else {     TCHAR     sErrMsg[256]; lErrMsg = CommDlgExtendedError; wsprintf(sErrMsg,TEXT("Error %d returned from GetOpenFileName"), lErrMsg); MessageBox(NULL, sErrMsg, TEXT("OpenDialog"), MB_OK); }

return lErrMsg; } Additional query words:

Keywords : kbdocfix kbCmnDlgFileO kbOSWinNT400 kbOSWin2000 kbGrpDSUser

Issue type : kbprb

Technology : kbAudDeveloper kbWin32sSearch kbWin32API