1、新建一个基于对话框的应用程序,工程名为RWTextFile。
2、如下图为对话框添加三个按钮,二个编辑框。
3、对编辑框设置如下:Multiline设置为true
4、对“写入文件”按钮进行添加响应函数OnWrite(),在相应函数OnWrite()中添加一下代码:void CRWText僻棍募暖FileDlg::OnWrite(){ UpdateData(true); CString strFilter,fileName,strText; strFilter="Text Files(*.txt)|*.txt||"; CFileDialog dlg(FALSE, NULL, NULL, OFN_EXPLORER|OFN_HIDEREADONLY| OFN_ENABLESIZING|OFN_FILEMUSTEXIST,strFilter); if(dlg.DoModal() == IDOK )//显示保存文件对话框 { fileName=dlg.GetPathName(); CFile savefile(fileName,CFile::modeCreate|CFile::modeWrite);//构造CFile对象 savefile.Write(m_strWrite,m_strWrite.GetLength());//写文件数据 savefile.Close();//关闭文件 } }
5、对“读取文件”按钮进行添加响应函数OnRead(),在相应函数OnRead()中添加一下代码:void CRWTextFileDlg::OnRead(){ CString str僻棍募暖Filter,fileName; strFilter="Text Files(*.txt)|*.txt||"; CFileDialog dlg(TRUE, NULL, NULL, OFN_EXPLORER|OFN_HIDEREADONLY|OFN_ENABLESIZING|OFN_FILEMUSTEXIST,strFilter); if(dlg.DoModal() == IDOK )//显示打开文件对话框 { fileName=dlg.GetPathName(); CFile openfile(fileName,CFile::modeRead);//构造CFile对象 int length=openfile.GetLength();//获取文件长度 char *strText; strText=new char[length]; openfile.Read(strText,length); openfile.Close();//关闭文件 m_strRead=(CString)strText; delete [] strText; UpdateData(false); }}
6、程序运行如下