could not save file using cfiledialog Saveas in MFC
Hi everyone,
I am trying to develop a GUI using MFC, but I am having trouble using CFiledialog to save a file. The problem is, the file is not getting saved to the folder when I use the CFiledialog. Below is the code I am using.
Code:
CString szFilter = "XNRep Files (*.xnrep)|*.xnrep||";
CString s = "xnrep";
CString t = "";
CFileDialog fileDlg(FALSE, s, t, NULL, szFilter);
if(fileDlg.DoModal() == IDOK)
{
std::ofstream file;
file.open(fileDlg.GetFileName(),std::ios::out);
if (file != NULL)
{
file << (*assembly);
file.close();
}
}
After the file dialog opens up, I enter the name of the file and select OK button. But the file does not show up in the directory I am saving to. Any suggestions would be appreciated. Thanks.
Re: could not save file using cfiledialog Saveas in MFC
Try using GetPathName() instead of GetFileName().
Re: could not save file using cfiledialog Saveas in MFC
It worked, thanks for the suggestion GCDEF
Re: could not save file using cfiledialog Saveas in MFC
Before posting, please format you code and use code tags. Go Advanced, select the code and click '#'.
Re: could not save file using cfiledialog Saveas in MFC
An additional note:
Once you are using MFC, it has no much sense to mix STL stuff if it's not necessary.
MFC has its own classes for dealing with files, like CFile and CStdioFile.
Example
Code:
CString strFilter = _T("XNRep Files (*.xnrep)|*.xnrep||");
CString strDefExt = _T("xnrep");
CString strToWrite = _T("Baba Safta");
CFileDialog dlgFile(FALSE, strDefExt, NULL, NULL, strFilter);
if(IDOK == dlgFile.DoModal())
{
CString strPathName = dlgFile.GetPathName();
try
{
CStdioFile file(strPathName, CFile::modeWrite|CFile::modeCreate);
file.WriteString(strToWrite);
}
catch(CException* e)
{
e->ReportError(); // show what's going wrong
e->Delete();
}
}
That way, it's much easier to handle UNICODE/ANSI strings, avoid leaks, handle errors, and last but not the least prevent headaches.