void COpenDlg::OnSave()
{
CString strPath,strText="";
char write[30000];
OPENFILENAME ofn;
ZeroMemory(&ofn,sizeof(ofn));
ofn.lStructSize=sizeof(ofn);
ofn.hwndOwner=this->GetSafeHwnd();
ofn.lpstrFilter="All Files(*.txt)\0*.txt\0\0";
ofn.lpstrCustomFilter=NULL;
ofn.nFilterIndex=0;
char filename[128];
filename[0]='\0';
ofn.lpstrFile=filename;
ofn.nMaxFile=128;
ofn.lpstrFileTitle=NULL;
ofn.lpstrInitialDir=NULL;
ofn.lpstrTitle="保存文本文件\0";
ofn.Flags=OFN_FILEMUSTEXIST|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT;
ofn.lpstrDefExt=NULL;
if(GetSaveFileName(&ofn)==0)
return;
strPath=filename;
if(strPath.Right(4)!=".txt")
strPath+=".txt";
CFile file(_T(strPath),CFile::modeCreate|CFile::modeWrite);
m_Edit.GetWindowText(strText);
strcpy(write,strText);
file.Write(write,strText.GetLength());
file.Close();
MessageBox("保存完成!","保存提示");
}
运行效果如下:
若保存时文件已经存在,重名,则提示是否替换。
加入:OFN_OVERWRITEPROMPT才有文件重名替换提示。替换后,原文件内容全无,为保存的最新内容。
OFN_OVERWRITEPROMPT(来自MSDN)
Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.