10.9.7 Modifying the OpenDlg Dialog Box Procedure

You must modify the IDOK case in the OpenDlg dialog box procedure in order to open and check the size of the file that is selected by the user. Add the following statements immediately after the call to the AddExt function in the IDOK case of the OpenDlg dialog box procedure:

if ((hFile = OpenFile(OpenName, &OfStruct, OF_READ)) < 0) {
    sprintf(str, "Error %d opening %s.",
        OfStruct.nErrCode, OpenName);
    MessageBox(hDlg, str, NULL, MB_OK | MB_ICONHAND);
}

else {
    fstat(hFile, &FileStatus);
    if (FileStatus.st_size > MAXFILESIZE) {
        sprintf(str,
            "Not enough memory to load %s.\n%s exceeds %ld bytes.",
            OpenName, OpenName, MAXFILESIZE);
        MessageBox(hDlg, str, NULL,
            MB_OK | MB_ICONHAND);
        return TRUE;
    }

    lstrcpy(FileName, OpenName);
    EndDialog(hDlg, hFile);
    return TRUE;
    }

The OpenFile function opens the specified file for reading and, if successful, returns a file handle. If the file cannot be opened, the case displays a message box containing the error number generated by MS-DOS. If the file is opened, the C run-time fstat function copies information about the file into the FileStatus structure. The file size is checked to make sure the file does not exceed the maximum size given by the MAXFILESIZE constant. The case displays an error message if the size is too big. Otherwise, the strcpy function copies the new name to the FileName variable and the EndDialog function terminates the dialog box and returns the file handle, hFile, to the DialogBox function.