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

下面的代码可以读取指定文件家中的所有文件和文件夹中格式为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. 在asp.net mvc中上传大文件

    在asp.net mvc 页面里上传大文件到服务器端,需要如下步骤: 1. 在Control类里添加get 和 post 方法 // get method public ActionResult Up ...

  2. response content-type json

    2015年11月3日 15:47:43 百度知道:ajax开发中在请求服务器端的响应时, 对于每一种返回类型 规范的做法是要在服务端指定response的contentType 常遇到下面的几种情况: ...

  3. Zookeeper集群服务部署

    Zookeeper是一个分布式.开源的分布式应用程序协调服务,是Google的Chubby的开源实现,也是和Hadoop.Hbase相互配合的重要组件,作用就是为分布式应用程序提供一致性服务,包括配置 ...

  4. 基于NHibernate的开发框架的设计

    上次的 NHibernate的Session管理策略和NHibernateHelper 发布并提供下载,给NHibernate刚入门的同学们带来很多便利. 最近有同学在求NH的通用仓储,正好我最近也设 ...

  5. codeforces 338(Div 2) B. Longtail Hedgehog 解题报告

    题目链接:http://codeforces.com/problemset/problem/615/B 题目意思:要画一只 hedgehog,由 tail 和 spines 组成.我们要求得 beau ...

  6. 解决Windows10下80端口被PID为4的System占用的问题

    一.背景 最近由于好奇心,更新了windows10系统,感觉上手还蛮快,而且体验还不错,但是在IDEA中做开发时,使用80端口进行启动项目的时候发现端口被占用了,于是尝试解决这个问题.具体步骤如下,分 ...

  7. 高效使用你的Xcode

    (via:VongLo's Dev Space  原文:Supercharging Your Xcode Efficiency)   好莱坞电影里经常看到黑客们手指在键盘上飞速跳跃,同时终端上的代码也 ...

  8. Javaweb---Servlet过滤器

    Servlet过滤器从字面上的字意理解为景观一层次的过滤处理才达到使用的要求,而其实Servlet过滤器就是服务器与客户端请求与响应的中间层组件,在实际项目开发中Servlet过滤器主要用于对浏览器的 ...

  9. inode

    硬盘的最小存储单位叫"扇区(sector)",每个扇区存储512字节(相当于0.5kb).系统读取硬盘时,只会读取多个sector即一个block.block 是文件存取的最小单位 ...

  10. CLR via C#学习笔记----知识总概括

    第1章 CLR的执行模型 托管模块的各个组成部分:PE32或PE32+头,CLR头,元数据,IL(中间语言)代码. 高级语言通常只公开了CLR的所有功能的一个子集.然而,IL汇编语言允许开发人员访问C ...