由于经常有读取一个文件夹中的很多随机编号的文件,很多时候需要读取某些特定格式的所有文件。

下面的代码可以读取指定文件家中的所有文件和文件夹中格式为jpg的文件

参考:

http://www.2cto.com/kf/201407/316515.html

http://bbs.csdn.net/topics/390124159

 

解决Win10下_findnext()异常

在win10中,使用文件遍历函数_findnext会报0xC0000005错误
原因:
_findnext()第一个参数”路径句柄”,返回的类型为intptr_t(long long),如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t

 

情形1: 读取一个文件夹中的所有目录

C++读取文件夹中所有的文件或者是特定后缀的文件
/*************************************************************
windows遍历文件目录以及子目录 所有的文件 总结
2018.2.27
*************************************************************/

#include <io.h>
#include <string>
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include <direct.h>  
#include <opencv2/opencv.hpp>
#include <opencv2/opencv_lib.h>
using namespace std;
using namespace cv;

/*************************************************************
方法4 先找出所有的目录和子目录,之后遍历各个目录文件
*************************************************************/
vector<string> folder;
void findAllSubDir(string  srcpath)
{
    //cout << "父目录  " << srcpath << endl;
    _finddata_t file;
    long lf;
    string pathName, exdName;
    //修改这里选择路径和要查找的文件类型  
    if ((lf = _findfirst(pathName.assign(srcpath).append("\\*").c_str(), &file)) == -1l)
        //_findfirst返回的是long型;long __cdecl _findfirst(const char *, struct _finddata_t *)  
        cout << "文件没有找到!\n";
    else
    {
        //cout << "\n文件列表:\n";
        do {
            string  curpath = file.name;
            if (curpath != "." && curpath != "..")
            {
                if (file.attrib == _A_NORMAL)cout << "  普通文件  ";
                else if (file.attrib == _A_RDONLY)cout << "  只读文件  ";
                else if (file.attrib == _A_HIDDEN)cout << "  隐藏文件  ";
                else if (file.attrib == _A_SYSTEM)cout << "  系统文件  ";
                else if (file.attrib == _A_SUBDIR)
                {
                    cout << "  子目录  ";
                    curpath = srcpath + "\\" + curpath;
                    cout << curpath << endl;
                    folder.push_back(curpath);
                    //变量子目录
                    //cout << "         ";
                    findAllSubDir(curpath);
                }
                else
                    ;//cout << "  存档文件  ";
                //cout << endl;
            }
        } while (_findnext(lf, &file) == 0);
        //int __cdecl _findnext(long, struct _finddata_t *);如果找到下个文件的名字成功的话就返回0,否则返回-1  
    }
    _findclose(lf);
}

int main()
{
    //要遍历的目录
    string path = "parent";
    findAllSubDir(path);
    vector<string> files = folder;
    int size = files.size();
    //     for (int i = 0; i < size; i++)
    //     {
    //         cout << files[i] << endl;
    //     }
    system("pause");
    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-14
  • 2022-12-23
  • 2021-09-05
  • 2021-09-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-09
  • 2022-12-23
相关资源
相似解决方案