Search code examples
cvisual-studiowinapiwin32gui

Win32 GetSaveFileName() return is nonzero but file isnt saved?


I am currently setting up an Editor using Win32 as a challenge for myself but my Method for saving the file for some reason doesnt save the file. I checked multiple times with my resources and looked over threads on the internet but I either didnt have the problem that got solved there in the first place or it didnt help at all. Am I overseeing something here?

void SaveUserFile(HWND hwnd)
{
    OPENFILENAME ofn;
    char szFile[MAX_PATH] = "";

    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFile = szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.hwndOwner = hwnd;
    ofn.nMaxFile = MAX_PATH;
    ofn.lpstrFilter = TEXT("Text document(*.txt*)\0*.txt\0Word 2016 document(*.docx*)\0*.docx\0All Files(*.*)\0*.*\0");
    ofn.nFilterIndex = 1;
    ofn.lpstrInitialDir = NULL;
    ofn.lpstrFileTitle = NULL;
    ofn.lpstrDefExt = "mp";
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;

    GetSaveFileName(&ofn);
}

Solution

  • GetSaveFileName does not save a file. It shows a dialog which allows the user to select a file name. If this returns successfully the program must then write the code to save the file, using the file name provided by the user which the program can read in szFile.

    In new programs you should use the common item dialogs (IFileOpenDialog and IFileSaveDialog) rather than GetOpenFileName and GetSaveFileName. There are numerous reasons for this, but one of the most obvious is that you will not be limited in file name length.