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();