Opening a File

This topic describes sample code that displays an Open dialog box so a user can specify the drive, directory, and name of a file to open. The sample code first initializes an OPENFILENAME structure, and then calls the GetOpenFileName function to display the dialog box.

In this example, the lpstrFilter member points to a buffer that specifies two filename filters that the user can select to limit the filenames that are displayed. The buffer contains a double-null terminated array of strings in which each pair of strings specifies a filter. The nFilterIndex member specifies that the first pattern is used when the dialog box is created.

This example sets the OFN_PATHMUSTEXIST and OFN_FILEMUSTEXIST flags in the Flags member. These flags cause the dialog box to verify, before returning, that the path and filename specified by the user actually exist.

The GetOpenFileName function returns TRUE if the user clicks the OK button and the specified path and filename exist. In this case, the buffer pointed to by the lpstrFile member contains the path and filename. The sample code uses this information in a call to the CreateFile function to open the file.

Although this example does not set the OFN_EXPLORER flag, it still displays the default Explorer-style Open dialog box. However, if you want to provide a hook procedure or a custom template and you want the Explorer user interface, you must set the OFN_EXPLORER flag.

OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for filename
HWND hwnd;              // owner window
HANDLE hf;              // file handle

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box. 

if (GetOpenFileName(&ofn)==TRUE) 
    hf = CreateFile(ofn.lpstrFile, GENERIC_READ,
        0, (LPSECURITY_ATTRIBUTES) NULL,
        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
        (HANDLE) NULL);