MFC 文件的操作

1.获取当前EXE文件的路径

TCHAR szPath[MAX_PATH];  
GetModuleFileName(NULL, szPath, MAX_PATH);
CString PathName(szPath);// PathName为当前EXE文件的路径,其中包括xxx.exe

2.MFC文件的创建以及写文件

CString m_strCurPath;
TCHAR szPath[MAX_PATH];  
GetModuleFileName(NULL, szPath, MAX_PATH);
CString PathName(szPath);
m_strCurPath =  PathName.Left(PathName.ReverseFind(_T('\\')) + 1);
CString FileNameTxt;
FileNameTxt = m_strCurPath + _T("\\Setting.txt");


CFile m_rFile;
CFileFind fileFind;
if(fileFind.FindFile(FileNameTxt) )//如果文件存在,则删除文件
{
DeleteFile(FileNameTxt);
}
CFileException exp;
if(!m_rFile.Open(FileNameTxt,CFile::modeCreate | CFile::modeWrite )) 
{
AfxMessageBox( _T("创建记录文件失败!"));
return;
}
m_rFile.Write((LPCTSTR)str,str.GetLength());
m_rFile.Flush();
m_rFile.Close();

3.文件的读取

CString m_strCurPath;
TCHAR szPath[MAX_PATH];  
GetModuleFileName(NULL, szPath, MAX_PATH);
CString PathName(szPath);
m_strCurPath =  PathName.Left(PathName.ReverseFind(_T('\\')) + 1);
CString FileNameTxt;
FileNameTxt = m_strCurPath + _T("\\Setting.txt");


CFile m_rFile;
CFileFind fileFind;
if(fileFind.FindFile(FileNameTxt) )
{
//DeleteFile(FileNameTxt);
}
CFileException exp;
CString str = _T("");
//CStdioFile m_rFile;
CFileException ex;
if(m_rFile.Open(FileNameTxt,CFile::modeRead | CFile::shareDenyWrite, &ex)) 
{
//CFile SourceFile;//数据文件
CString SourceData;//定义一临时变量保存一条记录
CString strtmp;
//CFileException ex;
//SourceFile.Open(strFile,CFile::modeRead | CFile::shareDenyWrite, &ex);
CArchive ar(&m_rFile,CArchive::load);
while(NULL!=ar.ReadString(SourceData))//循环读取文件,直到文件结束
{ strtmp+=SourceData+"\n";
if(SourceData=="")
continue;//跳过文件头部的提示信息 
}
str = strtmp;//strtmp为读到的文件
  


}else
{
AfxMessageBox( _T("读取记录文件失败!"));
}

//m_rFile.Flush();
m_rFile.Close();


注意要在edit control中显示需要将回车转换一下info.Replace("\n","\r\n");


文件内容的读取(比较靠谱)

CStdioFile m_rFile;
CFileFind fileFind;


if(fileFind.FindFile(FilePath) )
{
//DeleteFile(FileNameTxt);
}
CFileException exp;
CString str = _T("");
//CStdioFile m_rFile;
CFileException ex;
if(m_rFile.Open(FilePath,CFile::modeRead | CFile::shareDenyWrite, &ex)) 
{
CString strtmp;

while(m_rFile.ReadString(strtmp))
{
str += strtmp;
}
}else
{
AfxMessageBox( _T("读取记录文件失败!"));
}
//m_rFile.Flush();
m_rFile.Close();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值