【问题标题】:MFC Save file dialogMFC 保存文件对话框
【发布时间】:2011-08-23 22:20:50
【问题描述】:

我正在编写一个 MFC C++ 应用程序,该应用程序有一个“另存为”按钮,用于将 .txt 文件保存到光盘。有了它,我正在尝试为文件覆盖添加额外的验证(如果存在具有相同文件名的文件,那么它应该询问用户是否要覆盖旧文件)。我已经用下面的代码试过了,但它并没有真正起作用。当我单击消息框上的否时,它应该重新打开另存为文件对话框,但它给了我两个错误:第一个是Debug assertion failed,第二个是Encountered an improper argument。我应该如何更好地做到这一点?这是代码:

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;
        }
    }

应该提到,错误发生在第 7 行,并且仅在通过while 的第二个循环中发生。

【问题讨论】:

    标签: c++ file mfc dialog


    【解决方案1】:

    您应该在构造函数中使用OFN_OVERWRITEPROMPT 标志。该标志通常是默认标志之一,但您已将标志设置为 0。因此,如果您这样做:

    CFileDialog FileDlg(FALSE, CString(".txt"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, CString(strFilter));
    
    if (FileDlg.DoModal() == IDOK)  
    {  
        model->sendToFile(CSToString(FileDlg.GetPathName()));
    }
    

    它应该工作。顺便说一句,GetPathName() 获取所选文件的完整路径,因此您无需分两步获取文件夹和文件名。

    【讨论】:

    • 我知道,但我需要文件名和文件路径。至于上述,它的工作。谢谢!
    【解决方案2】:

    尝试在while循环中包含以下行(作为while循环中的第一行)

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

    这一行在代码中的 while 循环之外

    【讨论】:

      【解决方案3】:

      如果文件存在,CFileDialog 可以自行检测并提示用户覆盖。

      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
      );
      

      只需为标志传递 OFN_OVERWRITEPROMPT。

      至于你的问题,在调试器中运行,当你得到这个断言时,按下重试按钮,看看问题出在哪里(你可能还需要查看调用堆栈)。也许您应该尝试将其放入 while 循环中:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多