背景:
针对基于MFC编写的程序,只能在指定路径下运行的情况
修改点:
采用相对路径
cpp
void SearchXMLFiles(const CString& ExePath)
{
//查找当前目录下的文件
//查找文件路径时,如果当前文件下没有.xml文件,但子目录下有,先用"*。*"查找到子目录,再利用"\\.xml"查找".xml"
CFileFind objFileDirFinder;
CString strDirsearchPath = CString(strExePath) + _T("\\*.*"); //跳转到当前目录
BOOL bFindDirResult = objFileDirFinder.FindFile(strDirSearchPath); //开始查找,返回一个BOOL值,不是文件或者目录
while(bFindDirResult)
{
bFindDirResult = objFileDirFinder.FindNextFile(); //找到真实的目录,通过FindNextFile()函数实现
if(objFileDirFinder.IsDots()) //忽略"."和".."目录:隐藏文件
{
continue;
}
//如果找到的是一个目录,则递归搜索其中的文件
if(objFileDirFinder.IsDirectory())
{
CString dir = objFileDirFinder.GetFilePath();
SearchXMLFiles(dir);
}
else
{
//检查文件的扩展名是否是"xml"
CString strFileName = objFileDirFinder.GetFileName();
if(strFileName.Right(4).CompareNoCase(L".xml") == 0)
{
CString strFilePath = objFileDirFinder.GetFilePath(); //得到xml工作路径
m_ComboFilePath.AddString(strFilePath);
}
}
}
objFileDirFinder.Close();
}
//查找文件路径,获取公共路径
BOOL OnInitDialog()
{
TCHAR szPath[MAX_PATH] = {0};
GetModuleFileName(NULL,szPath,MAX_PATH); //得到exe文件路径
CString strExePath = szPath;
//使用CString中的ReverseFind()函数找到最后一个反斜杠的位置
int LastBackSlashPos = strExePath.ReverseFind("\\");
//如果找到最后一个反斜杠
if(LastBackSlashPos != -1)
{
//截掉最后一个反斜杠以及后面的部分,得到上一级目录
strExePath = strExePath.Left(LastBackSlashPos);
int SecondBackSlashPos = strExePath.ReverseFind("\\");
//再次查找上一层目录
if(SecondBackSlashPos != -1)
{
strExePath = strExePath.Left(SecondBackSlashPos);
int SecondBackSlashPos = strExePath.ReverseFind("\\");
}
}
//添加所有的公共目录
strExePath += "\\source\\Test";
//递归查找所有的xml文件
SearchXMLFiles(strExePath);
return true;
}