Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MFC Save file dialog

Tags:

c++

file

dialog

mfc

I am writing an MFC C++ application that has a Save As button for saving a .txt file to the disc. With it I am trying to add an extra verification for file overwriting (if a file with the same filename exists, then it should query the user if he wants to overwrite the old file or not). I have tried this with the below code, but it doesn't really work. When I click No on the MessageBox, it should reopen the Save As file dialog, but instead it gives me two errors: the first one is Debug assertion failed, and the second one is Encountered an improper argument. How should I do this better? This is the code:

char strFilter[] = { "Text Files (*.txt)|*.txt|" }; 

    CFileDialog FileDlg(FALSE, CString(".txt"), NULL, 0, CString(strFilter)); 

    while(true)
    {
        if( FileDlg.DoModal() == IDOK ) // this is the line which gives the errors
        {
            agendaName = FileDlg.GetFileName(); //filename
            agendaPath = FileDlg.GetFolderPath(); //filepath (folders)

            if(model->agendaExists(CSToString(agendaPath+TEXT("\\")+agendaName))) // there is another file called the same way
            {
                if(MessageBox(TEXT("A file with the specified name already exists. Overwrite?"), TEXT("File exists"), MB_YESNO) != 6) // user clicked NO (do not overwrite file)
                {
                    continue;
                }

            }

            model->sendToFile(CSToString(agendaPath+TEXT("\\")+agendaName));  // the file is unique so the agenda named agendaName found at path agendaPath is saved
            return;
        }
    }

It should be mentioned that the errors occur on line 7 and only on the second loop through the while.

like image 836
Adrian Marinica Avatar asked May 12 '11 08:05

Adrian Marinica


1 Answers

CFileDialog can detect itself if a file exists and prompt the user for overwriting.

explicit CFileDialog(
   BOOL bOpenFileDialog,
   LPCTSTR lpszDefExt = NULL,
   LPCTSTR lpszFileName = NULL,
   DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
   LPCTSTR lpszFilter = NULL,
   CWnd* pParentWnd = NULL,
   DWORD dwSize = 0
);

Just pass OFN_OVERWRITEPROMPT for the flags.

As for your problem, run in Debugger and when you get that assertion press the Retry button to see where the problem comes from (you'll probably have to look through the call stack also). Maybe you should try putting this in the while loop:

CFileDialog FileDlg(FALSE, CString(".txt"), NULL, 0, CString(strFilter)); 
like image 125
Marius Bancila Avatar answered Nov 03 '22 09:11

Marius Bancila