ChooseFileSave

The ChooseFileSave function displays a Save As dialog box that lets the user choose the drive, directory, and filename for which to save a file. This function does not actually handle the saving of the file; it only allows the user to select the file. The application must then perform the save operation.

BOOL ChooseFileSave(
    LPSAVEFILENAME lpofn
);

Parameters

Parameter Description
lpofn A pointer to a SAVEFILENAME structure that contains information used to initialize the dialog box. The system uses this structure to return information about the filename selected by the user.

Return Value

Value Description
TRUE The user selected a file and the lStructSize member of the SAVEFILENAME structure is valid. The lpfnHook member of the SAVEFILENAME structure can be used to specify a hook procedure that processes messages for the dialog box.
FALSE The user canceled the dialog box or an error occurred. If the function fails, you can call GetLastError to get the extended error information.

Remarks

Example


#include <windows.h>
#include <commdlg.h>

// ...

void SaveFileExample() {
    OPENFILENAME ofn;
    char szFileName[MAX_PATH] = "";

    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
    ofn.lpstrFile = szFileName;
    ofn.nMaxFile = sizeof(szFileName);
    ofn.lpstrTitle = "Save As";
    ofn.Flags = OFN_OVERWRITEPROMPT; // Prompt user if file exists

    if (ChooseFileSave(&ofn)) {
        // User selected a file, 'szFileName' now contains the full path
        // Now you can proceed to open and write to the file
        HANDLE hFile = CreateFile(
            ofn.lpstrFile,
            GENERIC_WRITE,
            0,
            NULL,
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL
        );

        if (hFile != INVALID_HANDLE_VALUE) {
            // Write your data to the file
            DWORD bytesWritten;
            const char* dataToSave = "This is the content to save.";
            WriteFile(hFile, dataToSave, strlen(dataToSave), &bytesWritten, NULL);
            CloseHandle(hFile);
            MessageBox(NULL, "File saved successfully!", "Success", MB_OK);
        } else {
            MessageBox(NULL, "Failed to create file.", "Error", MB_OK | MB_ICONERROR);
        }
    } else {
        // User canceled or an error occurred
        if (CommDlgExtendedError() != 0) {
            MessageBox(NULL, "Dialog box error occurred.", "Error", MB_OK | MB_ICONERROR);
        }
    }
}
        

See Also

Related Function Description
ChooseFileOpen Displays an Open dialog box.
SAVEFILENAME Contains the information used to initialize a Save As dialog box.
CommDlgExtendedError Retrieves the extended error value for the last common dialog-box error.