MFC: 使用相对路径读取文件位置

背景:

针对基于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;
}
相关推荐
无限进步_1 天前
【C语言&数据结构】二叉树遍历:从前序构建到中序输出
c语言·开发语言·数据结构·c++·算法·github·visual studio
天赐学c语言1 天前
1.14 - 用栈实现队列 && 对模板的理解以及模板和虚函数区别
c++·算法·leecode
玖釉-1 天前
[Vulkan 学习之路] 02 - 万物起源:创建 Vulkan 实例 (Instance)
c++·windows·图形渲染
SunkingYang1 天前
QT如何读取csv文件
c++·qt·csv·读取文件
CoderCodingNo1 天前
【GESP】C++六级考试大纲知识点梳理, (2) 哈夫曼树、完全二叉树与二叉排序树
开发语言·c++
水饺编程1 天前
第4章,[标签 Win32] :获取设备环境句柄的第一个方法
c语言·c++·windows·visual studio
老四啊laosi1 天前
[C++初阶] 9. STL--string使用(二)
c++
SunkingYang1 天前
QT中如何使用QMessageBox 实现提示、警告、错误报告和用户决策功能
c++·qt·提示·错误·告警·用法·qmessagebox
Once_day1 天前
CC++八股文之内存
c语言·c++
量子炒饭大师1 天前
【C++入门】Cyber骇客的同名异梦——【C++重载函数】(与C的函数差异)
c语言·开发语言·c++·函数重载