基于C++和MFC遍历指定文件夹下指定格式的文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_25923849/article/details/78268984

最近工作中遇到需要读写文件的操作
针对单个模块和VC界面中有两种不同的操作方式,还有其他的没仔细研究,在这里记录一下。

先上代码

//c++版本
    _finddata_t file;
    int k;
    long HANDLE;
    string strFloderPath = "指定的文件夹路径";
    string strString = strFloderPath + "\\*.*";
    const char* str1 = strString.c_str();

    k = HANDLE = _findfirst(str1, &file);
    while (k != -1)
    {
        string strTemp = file.name;
        if (strTemp != "." && strTemp != "..")
        {
            int maxChar = strTemp.length();
            string rightFour = strTemp.substr(maxChar - 4, 4);
            if (".xxx" == rightFour)//需要的格式后缀
            {
                string strFilePath = strFloderPath + file.name;//路径
                DoSomething(strFilePath);//针对该文件的具体操作
            }
        }
        k = _findnext(HANDLE, &file);
    }
    _findclose(HANDLE);

//中间的函数可以查MSDN,头文件需要包含

//MFC版本
    CString fdPath;
    CString strDataPath = strFloderPath + "\\*.*";
    CString strTmp;

    CFileFind find;//MFC的文件查找类
    BOOL bf = find.FindFile(strDataPath);
    while (bf)//循环遍历文件夹下的文件
    {
        bf = find.FindNextFile();
        if (!find.IsDots())
        {
            fdPath = find.GetFilePath();
            strTmp = fdPath.Right(4);//CString很方便
            strTmp.MakeLower();
            if (".xxx" == strTmp)//指定格式后缀
            {
                DoSomething(fdPath);//针对文件的操作
            }
        }
    }
    find.Close();

MFC中对很多常用的操作进行了二次封装,函数功能齐全好用,如果界面中涉及到文件操作用MFC更方便。
C++的版本适用于单个模块中用到文件操作,封装不需要外部的MFC库。

猜你喜欢

转载自blog.csdn.net/sinat_25923849/article/details/78268984