牛骨文教育服务平台(让学习变的简单)
博文笔记

VC文件操作:保存文件对话框 OPENFILENAME 代码

创建时间:2015-02-05 投稿人: 浏览次数:1365


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)*.txt";
        ofn.lpstrCustomFilter=NULL;
        ofn.nFilterIndex=0;
        char filename[128];
        filename[0]="";
        ofn.lpstrFile=filename;
        ofn.nMaxFile=128;
        ofn.lpstrFileTitle=NULL;
        ofn.lpstrInitialDir=NULL;
        ofn.lpstrTitle="保存文本文件";
        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.



声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。