在基本对话框的应用程序中,拖入两个静态文本框,用于显示文件路径;拖入两个按钮一个为打开,一个为保存,在拖入一个编辑框,用于显示文件的内容。
首先为两个静态文本框和编辑框关联变量,以下是两个按钮的实现代码。
void CMy001Dlg::OnButton1() //打开按钮的代码
{
CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"All Files(*.TXT)|*.TXT||",AfxGetMainWnd());
CString strPath,strText="";
if(dlg.DoModal()==IDOK)
{
strPath=dlg.GetPathName();
m_Openpath.SetWindowText(strPath);
CFile file(strPath,CFile::modeRead);
//char read[10000];
//file.Read(read,10000);
int len=file.GetLength();
char * p=new char[len];
//char read[len];
file.Read(p,len);
for(int i=0;i<file.GetLength();i++)
{
strText+=*p;p++;
}
file.Close();
m_FileText.SetWindowText(strText);
}
}
void CMy001Dlg::OnButton2() //保存按钮的代码
{
// TODO: Add your control notification handler code here
CFileDialog dlg(FALSE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"All Files(*.TXT)|*.TXT||",AfxGetMainWnd());
CString strPath,strText="";
char write[10000];
if(dlg.DoModal()==IDOK)
{
strPath=dlg.GetPathName();
if(strPath.Right(4)!=".TEXT")
strPath+=".TEXT";
m_Savepath.SetWindowText(strPath);
CFile file(_T(strPath),CFile::modeCreate|CFile::modeWrite);
m_FileText.GetWindowText(strText);
strcpy(write,strText);
file.Write(write,strText.GetLength());
file.Close();
}
}