MFC应用实例:[43]读写文件
1、新建一个基于对话框的应用程序,工程名为RWFile。
![MFC应用实例:[43]读写文件](https://exp-picture.cdn.bcebos.com/e9a4f2eeadbcbe2ff5b1acab54dae43b3a867815.jpg)
2、如下图为对话框添加三个按钮,一个编辑框和一个文本控件。
![MFC应用实例:[43]读写文件](https://exp-picture.cdn.bcebos.com/e57a258602214f572a97b908732064fb970b7315.jpg)
3、为保存按钮添加响应函数OnButton1(),并在响应函数OnButton1()中添加一下代码:
void CRWFileDlg::OnButton1()
{
UpdateData(true); //更新控件数据到变量
char* fileName = "c:\\file.txt"; //保存信息的文件
CFile file;
CFileException fileException;
//CFile对象以创建和写的方式打开文件
if (!file.Open(fileName, CFile::modeCreate | CFile::modeWrite, &fileException))
{
//显示异常信息
CString errorInfo;
errorInfo.Format("不能打开文件%s, 错误:%u\n", fileName, fileException.m_cause);
MessageBox(errorInfo, "错误", MB_OK | MB_ICONERROR);
return;
}
file.Write((void*)(&m_word), sizeof(m_word));//将信息写入文件
file.Close(); //关闭文件
//显示成功保存信息
MessageBox("已将这句话成功保存到文件中。", "信息", MB_OK | MB_ICONINFORMATION);
m_word = 0; //清空信息
UpdateData(false);//更新视图
}
![MFC应用实例:[43]读写文件](https://exp-picture.cdn.bcebos.com/974a2f21056104a39428691d63d7592ae2ef6b15.jpg)
4、为读取按钮添加响应函数OnButton2(),并在响应函数OnButton2()中添加一下代码:
void CRWFileDlg::OnButton2()
{
char* fileName = "c:\\file.txt"; //保存信息的文件
CFile file;
CFileException fileException;
//CFile对象以读的方式打开文件
if (!file.Open(fileName, CFile::modeRead, &fileException))
{
//显示异常信息
CString errorInfo;
errorInfo.Format("不能打开文件%s, 错误:%u\n", fileName, fileException.m_cause);
MessageBox(errorInfo, "错误", MB_OK | MB_ICONERROR);
return;
}
file.Read((void*)(&m_word), sizeof(m_word));//将信息写入文件
file.Close(); //关闭文件
UpdateData(false); //更新对话框视图
//显示成功读取信息
MessageBox("已成功从文件中读取到了这句话。", "信息", MB_OK | MB_ICONINFORMATION);
}
![MFC应用实例:[43]读写文件](https://exp-picture.cdn.bcebos.com/1570c1b6326c5766520ee8e0a4632385e1366115.jpg)
5、程序运行如下:写入一句话,并进行读取。
![MFC应用实例:[43]读写文件](https://exp-picture.cdn.bcebos.com/46a92de039723d036e2bd435bb486143d6d45715.jpg)
![MFC应用实例:[43]读写文件](https://exp-picture.cdn.bcebos.com/49701aebf6a75f0f5cea9e5d97324b18502c4c15.jpg)