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

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

参考:

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

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

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

/*************************************************************
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) == );
//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 ;
}

情形2: 读取一个文件夹中的所有文件

更新2017.7.28

 /*************************************************************
windows遍历文件目录以及子目录 所有的文件 总结
2017.7.28
*************************************************************/ #include <io.h>
#include <string>
#include <fstream>
#include <string>
#include <vector>
using namespace std; /*************************************************************
方法1 不能遍历子目录
*************************************************************/
//获取所有的文件名
void GetAllFiles(string path, vector<string>& files)
{
long hFile = ;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != && strcmp(fileinfo.name, "..") != )
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
GetAllFiles(p.assign(path).append("\\").append(fileinfo.name), files);
}
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == );
_findclose(hFile);
}
} //获取特定格式的文件名
void GetAllFormatFiles(string path, vector<string>& files, string format)
{
//文件句柄
long hFile = ;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != && strcmp(fileinfo.name, "..") != )
{
//files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
GetAllFormatFiles(p.assign(path).append("\\").append(fileinfo.name), files, format);
} }
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == );
_findclose(hFile);
}
} // 该函数有两个参数,第一个为路径字符串(string类型,最好为绝对路径);
// 第二个参数为文件夹与文件名称存储变量(vector类型,引用传递)。
// 在主函数中调用格式(并将结果保存在文件"AllFiles.txt"中,第一行为总数):
int readfile(string filePath)
{
//string filePath = "testimages\\water";
vector<string> files;
char * distAll = "AllFiles.txt";
//读取所有的文件,包括子文件的文件
//GetAllFiles(filePath, files);
//读取所有格式为jpg的文件
string format = ".txt";
GetAllFormatFiles(filePath, files, format);
ofstream ofn(distAll);
int size = files.size();
ofn << size << endl;
for (int i = ; i < size; i++)
{
ofn << files[i] << endl;
cout << files[i] << endl;
}
ofn.close();
return ;
} /*************************************************************
方法2 不能遍历子目录
*************************************************************/
void readfile1()
{
_finddata_t file;
long lf;
//修改这里选择路径和要查找的文件类型
if ((lf = _findfirst("D:\\project\\dualcamera\\TestImage\\FileTest\\c1\\s1\\*.txt*", &file)) == -1l)
//_findfirst返回的是long型;long __cdecl _findfirst(const char *, struct _finddata_t *)
cout << "文件没有找到!\n";
else
{
cout << "\n文件列表:\n";
do {
cout << file.name;
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 << " 子目录 ";
else cout << " 存档文件 ";
cout << endl;
} while (_findnext(lf, &file) == );
//int __cdecl _findnext(long, struct _finddata_t *);如果找到下个文件的名字成功的话就返回0,否则返回-1
}
_findclose(lf);
} /*************************************************************
方法3 可以遍历子目录
*************************************************************/
void dir(string path)
{
long hFile = ;
struct _finddata_t fileInfo;
string pathName, exdName;
// \\* 代表要遍历所有的类型
if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -)
{
return;
}
do
{
//判断文件的属性是文件夹还是文件
string curpath = fileInfo.name;
if (curpath != "." && curpath != "..")
{
curpath = path + "\\" + curpath;
//变量文件夹中的png文件
if (fileInfo.attrib&_A_SUBDIR)
{
//showfile(curpath);
dir(curpath);
}
else
{
cout << curpath << endl;
}
}
//cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
} while (_findnext(hFile, &fileInfo) == );
_findclose(hFile);
return;
} /*************************************************************
方法4 先找出所有的目录和子目录,之后遍历各个目录文件
*************************************************************/
vector<string> folder;
void dir(string path)
{
long hFile = ;
struct _finddata_t fileInfo;
string pathName, exdName;
//* 代表要遍历所有的类型
if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -) {
return;
}
do
{
//判断文件的属性是文件夹还是文件
string curpath = fileInfo.name;
if (curpath != "." && curpath != "..")
{
curpath = path + "\\" + curpath;
//变量文件夹中的png文件
if (fileInfo.attrib&_A_SUBDIR)
{
//当前文件是目录
dir(curpath);
cout << curpath << endl;
}
else
{
//进入某个子目录了
cout << curpath << endl;
}
}
//cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
} while (_findnext(hFile, &fileInfo) == );
_findclose(hFile);
return;
} void findAllSubDir(string srcpath)
{
_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);
//变量子目录
findAllSubDir(curpath);
}
else
;//cout << " 存档文件 ";
//cout << endl;
}
} while (_findnext(lf, &file) == );
//int __cdecl _findnext(long, struct _finddata_t *);如果找到下个文件的名字成功的话就返回0,否则返回-1
}
_findclose(lf);
} int main()
{
//要遍历的目录
string path = "FileTest";
//dir(path);
findAllSubDir(path);
vector<string> files = folder;
//char * distAll = "AllFiles.txt";
//ofstream ofn(distAll);
int size = files.size();
//ofn << size << endl;
for (int i = ; i < size; i++)
{
//ofn << files[i] << endl;
cout << files[i] << endl;
readfile(files[i]);
}
system("pause");
return ;
}
//windows 获取某个目录下的所有文件的文件名
#include <io.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std; //获取所有的文件名
void GetAllFiles( string path, vector<string>& files)
{
    long hFile = 0;
    //文件信息
    struct _finddata_t fileinfo;
    string p;
    if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) != -1)
    {
        do
        {
            if((fileinfo.attrib & _A_SUBDIR))
            {
                if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0)
                {
                    files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
                    GetAllFiles( p.assign(path).append("\\").append(fileinfo.name), files );
                }
            }
            else
            {
                files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
            }
        }while(_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}   //获取特定格式的文件名
void GetAllFormatFiles( string path, vector<string>& files,string format)
{
    //文件句柄
    long hFile = 0;
    //文件信息
    struct _finddata_t fileinfo;
    string p;
    if((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(),&fileinfo)) != -1)
    {
        do
        {
            if((fileinfo.attrib & _A_SUBDIR))
            {
                if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0)
                {
                    //files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
                    GetAllFormatFiles( p.assign(path).append("\\").append(fileinfo.name), files,format);
                }             }
            else
            {
                files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
            }
        }while(_findnext(hFile, &fileinfo) == 0);
       _findclose(hFile);
    }
} // 该函数有两个参数,第一个为路径字符串(string类型,最好为绝对路径);
// 第二个参数为文件夹与文件名称存储变量(vector类型,引用传递)。
// 在主函数中调用格式(并将结果保存在文件"AllFiles.txt"中,第一行为总数):
int main()
{
    string filePath = "testimages\\water";
    vector<string> files;
    char * distAll = "AllFiles.txt";
    //读取所有的文件,包括子文件的文件
    //GetAllFiles(filePath, files);
    //读取所有格式为jpg的文件
    string format = ".jpg";
    GetAllFormatFiles(filePath, files,format);
    ofstream ofn(distAll);
    int size = files.size();
    ofn<<size<<endl;
    for (int i = 0;i<size;i++)
    {
        ofn<<files[i]<<endl;
        cout<< files[i] << endl;
    }
    ofn.close();
    return 0;
}
//LINUX/UNIX c获取某个目录下的所有文件的文件名

#include <stdio.h>
#include <dirent.h>
void main(int argc, char * argv[])
{
char ch,infile[],outfile[];
struct dirent *ptr;
DIR *dir;
dir=opendir("./one");
while((ptr=readdir(dir))!=NULL)
{ //跳过'.'和'..'两个目录
if(ptr->d_name[] == '.')
continue;
printf("%s is ready...\n",ptr->d_name);
sprintf(infile,"./one/%s",ptr->d_name); printf("<%s>\n",infile);
}
closedir(dir);
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;


int readFileList(char *basePath, vector<string> &filelist)
{
DIR *dir;
struct dirent *ptr;
char base[1000];


if ((dir=opendir(basePath)) == NULL)
{
perror("Open dir error...");
exit(1);
}


while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir
continue;
else if(ptr->d_type == 8) ///file
{
printf("d_name:%s/%s\n",basePath,ptr->d_name);
string filestr = basePath;
filestr = filestr + "/" + ptr->d_name;
filelist.push_back(filestr);
}
else if(ptr->d_type == 10) ///link file
printf("d_name:%s/%s\n",basePath,ptr->d_name);
else if(ptr->d_type == 4) ///dir
{
memset(base,'\0',sizeof(base));
strcpy(base,basePath);
strcat(base,"/");
strcat(base,ptr->d_name);
readFileList(base, filelist);
}
}
closedir(dir);
return 1;
}


int main(void)
{
DIR *dir;
char *basePath = "./test";
printf("the current dir is : %s\n",basePath);
vector<string> filelist;
readFileList(basePath, filelist);
for(int i =0; i < filelist.size(); ++i)
{
cout << filelist[i] << endl;
}
return 0;
}


//删除指定的文件类型
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <iostream>
using namespace std; int readFileList(char *basePath, string fileext)
{
    DIR *dir;
    struct dirent *ptr;
    char base[1000];     if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }     while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8)    ///file
        {
            //printf("d_name:%s/%s\n",basePath,ptr->d_name);
            string temp = ptr->d_name;
            cout  << temp << endl;
            string sub = temp.substr(temp.length() - 4, temp.length()-1);
            cout  << sub << endl;
            if(sub == fileext)
            {
                string path = basePath;
                path += "/";
                path += ptr->d_name;
                int state = remove(path.c_str());
            }
        }
        else if(ptr->d_type == 10)    ///link file
        {
            printf("d_name:%s/%s\n",basePath,ptr->d_name);
        }
        else if(ptr->d_type == 4)    ///dir
        {
            memset(base,'\0',sizeof(base));
            strcpy(base,basePath);
            strcat(base,"/");
            strcat(base,ptr->d_name);
            readFileList(base);
        }
    }
    closedir(dir);
    return 1;
} int main(void)
{
    DIR *dir;
    char *basePath = "../dlib-android-app";
    printf("the current dir is : %s\n",basePath);
    string fileext = ".txt"
    readFileList(basePath, fileext);
    return 0;
}

//读取文件到一个vector中,并复制到另外一个文件夹

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>  
#include <sys/stat.h> using namespace std; #define dmax(a,b) (((a) > (b)) ? (a) : (b))
#define dmin(a,b) (((a) < (b)) ? (a) : (b)) //获取特定格式的文件名
int readFileList(std::vector<string> &filelist, const char *basePath, string format)
{
DIR *dir;
struct dirent *ptr;
char base[]; if ((dir=opendir(basePath)) == NULL)
{
perror("Open dir error...");
exit();
} while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")== || strcmp(ptr->d_name,"..")==) ///current dir OR parrent dir
continue;
else if(ptr->d_type == ) //file
{
//printf("d_name:%s/%s\n",basePath,ptr->d_name);
string temp = ptr->d_name;
//cout << temp << endl;
string sub = temp.substr(temp.length() - , temp.length()-);
//cout << sub << endl;
if(sub == format)
{
string path = basePath;
path += "/";
path += ptr->d_name;
filelist.push_back(path);
}
}
else if(ptr->d_type == ) ///link file
{
//printf("d_name:%s/%s\n",basePath,ptr->d_name);
}
else if(ptr->d_type == ) ///dir
{
memset(base,'\0',sizeof(base));
strcpy(base,basePath);
strcat(base,"/");
strcat(base,ptr->d_name);
readFileList(filelist, base, format);
}
}
closedir(dir);
return ;
} void findDir(string src, string &dst, string filePath)
{
int begin = src.find(filePath) + filePath.size() + ;
int end = ;
for (int i = src.size() - ; i >= ; --i)
{
//cout << src[i] << endl;
if (src[i] == '/')
{
end = i - ;
break;
}
}
//cout << begin << endl;
//cout << end << endl;
dst = src.substr(begin, end - begin + );
} int main()
{
// Loop over all the images provided on the command line.
std::vector<string> files;
string filePath = "./lfw_small_raw";
string format = ".jpg";
printf("the current dir is : %s\n", filePath.c_str());
readFileList(files, filePath.c_str(), format);
string alignpath = "./lfw_small_align";
for (int i = ; i < files.size(); ++i)
{
/* code */
cout << files[i] << endl;
string name;
findDir(files[i], name, filePath);
cout << name << endl;
     //判断目录是否存在,并创建新目录
        string newname = alignpath + "/" + name;
        if (access(newname.c_str(), 0) == -1)  
        {
            int flag=mkdir(newname.c_str(), 0777);  
        }
}
}

C++读取文件夹中所有的文件或者是特定后缀的文件的更多相关文章

  1. [R语言]读取文件夹下所有子文件夹中的excel文件,并根据分类合并。

    解决的问题:需要读取某个大文件夹下所有子文件夹中的excel文件,并汇总,汇总文件中需要包含的2部分的信息:1.该条数据来源于哪个子文件夹:2.该条数据来源于哪个excel文件.最终,按照子文件夹单独 ...

  2. 生成一个文件夹中的所有文件的txt列表

    1.windows操作系统中 1.用管理员运行打开dos界面: 2.用cd转到相应的文件夹中: 3.用dir /b /on >list.txt来生成文件列表的txt. 2.Mac系统中 1.打开 ...

  3. webpack 打包出多个HTML文件,多个js文件,图片文件放置到指定文件夹中

    一.webpack.config.js简单代码 const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { ...

  4. python复制文件到文件夹中

    目标:将一张图片复制到一个文件夹下 所有子文件中. import shutil import os #第一部分,准备工作,拼接出要存放的文件夹的路径 file = 'E:/测试/1.jpg' #cur ...

  5. 使用ftp读取文件夹中的多个文件,并删除

    public class FTPUtils { private static final Logger LOG = LoggerFactory.getLogger(FTPUtils.class); / ...

  6. python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件

    python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 python操作txt文件中 ...

  7. C# 读取指定文件夹中的全部文件,并按规则生成SQL语句!

    本实例的目的在于: 1 了解怎样遍历指定文件夹中的全部文件 2 控制台怎样输入和输出数据 代码: using System; using System.IO; namespace ToSql{ cla ...

  8. WPF获取读取电脑指定文件夹中的指定文件的地址

    //保存指定文件夹中的指定文件的地址 string List<string> mListUri = new List<string>(); //文件夹地址 string fol ...

  9. MATLAB读取一个文件夹下的多个子文件夹中的多个指定格式的文件

    MATLAB需要读取一个文件夹下的多个子文件夹中的指定格式文件,这里以读取*.JPG格式的文件为例 1.首先确定包含多个子文件夹的总文件夹 maindir = 'C:\Temp Folder'; 2. ...

随机推荐

  1. 在VS中MFC、ATL与WIN32有什么联系或区别?

    有时候遇到一些初学者问我这个问题:在VS中使用MFC和ATL与使用WIN32有什么联系或区别?通俗来说,win32是通过调用windows api去实现需要的功能.而MFC和ATL是封装好的类库,包含 ...

  2. 数学软件 之 基于MATLAB的DFP算法

    DFP算法是本科数学系中最优化方法的知识,也是无约束最优化方法中非常重要的两个拟Newton算法之一,上一周写了一周的数学软件课程论文,姑且将DFP算法的实现细节贴出来分享给学弟学妹参考吧,由于博客不 ...

  3. 9. javacript高级程序设计-客户端检测

    1. 客户端检测 1.1 能力检测 在编写代码之前先检测特定浏览器的能力. 1.2 怪癖检测 怪癖实际上是浏览器实现中的bug 1.3 用户代理检测 通过检测用户代理字符串来识别浏览器.用户代理字符串 ...

  4. DataStage

    parallel job shell调用:dsjob ./dsjob -run -mode NORMAL -paramfile xxx.param <PROJECT> <JOB> ...

  5. [第三方]AFNetWorking3.0网络框架使用方法

    官网地址https://github.com/AFNetworking/AFNetworking #import <AFNetworking.h> - (void)viewDidLoad ...

  6. OKhttp的封装(上)

    自从介绍了OKhttp3的一些基本使用之后,又偷了下懒,所以它的续篇被搁置了一段时间,现在补充. OKhttpManager.Class  请求工具类 package com.example.admi ...

  7. POJ 3597 Polygon Division (DP)

    题目链接 题意:把一个正多边形分成数个三角形或者四边形,问有多少种方案. 题解: 如果分出的全为三角形的话,那就是正多边形三角剖分问题.它的结果就是Catalan数.现在也可以划分出四边形的话,可以采 ...

  8. jsonp注意事项

    自己测试的: <?php ');                     }                 }); } </script>     <!DOCTYPE htm ...

  9. EasyUI中控件汉化问题

    --BY ZYZ 我在使用EasyUI的过程中,遇到了控件无汉化的情况,如下图. 这么多洋文看着觉得挺烦的.时间居然是月日年格式的,这样可不行,得改. 重写控件代码?别,那能是我这种低级代码C-V客能 ...

  10. sendto : Permission denied

    遇到如题的问题,google了一番,找到了解决方法,写下来备用 问题: udp发送数据时候报错sendto error  : Permission denied 改正方法: 在创建了套接字后,加上下列 ...