一,写文件
void CdrawView::OnFileWrite()
{
CString hello = _T("hello,word!");
//对话框以打开方式
CFileDialog fileDlg(false);
if (IDOK == fileDlg.DoModal())
{
//获取对话框返回的文件名
CString path = fileDlg.GetPathName();
//打开文件
CFile file(path, CFile::modeWrite | CFile::modeCreate);
//写入
int len = hello.GetLength() * sizeof(TCHAR);
file.Write(hello, len);
file.Close();
}
}
二,读文件
void CdrawView::OnFileRead()
{
//读文件方式
CFileDialog fileDlg(true);
if (IDOK == fileDlg.DoModal())
{
//获取文件名
CString path = fileDlg.GetPathName();
//以读方式打开文件
CFile file(path,CFile::modeRead);
//准备缓冲区
TCHAR* pBuf;
int cnt = file.GetLength();
//一个字符占2个字节,除以TCHAR 得到共几个字符。
int chars = cnt / sizeof(TCHAR);
//由于有一个结束位0,所以加1
pBuf = new TCHAR[chars + 1];
//读文件到缓冲区
file.Read(pBuf, cnt);
//设置字符串结束位置
pBuf[chars] = 0;
MessageBox(pBuf);
file.Close();
delete[] pBuf;
}
}