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

下面的代码可以读取指定文件家中的所有文件和文件夹中格式为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. 《Head First Servlet JSP》学习笔记二

    一. 二. 三. 四. 五. 六. 七. 八. 九. 十. 十一. 十二.  

  2. js里面的 InttoStr 和 StrtoInt

    javascript 字符串 和 数字的转换,话说好灵活,感觉回不去pascal了 int转换string: 1,var str=String(int); 2,num.toString(param) ...

  3. C++ 代码头注释模板

    /********************************************************************************* *Copyright(C),You ...

  4. MinGW平台 openjpeg-2.1.0 静态编译后未定义引用的解决方法

    undefined reference to __imp_opj_xxx keyword: ffmpeg,openjpeg,OPJ_EXPORTS,OPJ_STATIC,opj_version,__i ...

  5. [转][Android]FragmentPagerAdapter与FragmentStatePagerAdapter使用详解与区别

    原文链接:http://blog.csdn.net/zhaokaiqiang1992 FragmentPagerAdapter是android-support-v4支持包里面出现的一个新的适配器,继承 ...

  6. jQueryUI Datepicker的使用

    jQueryUI Datepicker是一个高度可定制的插件,可以很方便的为你的页面添加日期选择功能,你可以自定义日期的显示格式 以及要使用的语言. 你可以使用键盘的快捷键来驱动datepicker插 ...

  7. sql server 导出表结构

    今天准备整理下手里面几个数据库,形成一个表结构文档,方便以后维护使用. 网上找到一个脚本还不错,小小的修改就满足了我的要求,执行完SQL脚本. 在结果就能看到数据库所有表的结构,这个时候只要全选,然后 ...

  8. 【leetcode】Compare Version Numbers(middle)

    Compare two version numbers version1 and version2.If version1 > version2 return 1, if version1 &l ...

  9. window.parent 与 window.opener

    window.parent针对iframe,window.opener针对window.open 父页面parent.jsp: <%@ page language="java" ...

  10. 在Eclipse中手动安装pydev插件,eclipse开发python环境配置

    最近在学习Python,因为我是做java的,用惯了eclipse,所以就想用eclipse开发python,但是配置开发环境的时候发现按照网上的配置大多不行,而且都是用的在线安装,很垃圾,没办法,自 ...