C++读取文件夹中所有的文件或者是特定后缀的文件

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

下面的代码可以读取指定文件家中的所有文件和文件夹中格式为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) == 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

 

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

 

更新2017.7.28

  1 /*************************************************************
  2 windows遍历文件目录以及子目录 所有的文件 总结
  3 2017.7.28
  4 *************************************************************/
  5 
  6 #include <io.h>
  7 #include <string>
  8 #include <fstream>
  9 #include <string>
 10 #include <vector>
 11 using namespace std;
 12 
 13 /*************************************************************
 14 方法1 不能遍历子目录
 15 *************************************************************/
 16 //获取所有的文件名
 17 void GetAllFiles(string path, vector<string>& files)
 18 {
 19     long hFile = 0;
 20     //文件信息
 21     struct _finddata_t fileinfo;
 22     string p;
 23     if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
 24     {
 25         do
 26         {
 27             if ((fileinfo.attrib & _A_SUBDIR))
 28             {
 29                 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
 30                 {
 31                     files.push_back(p.assign(path).append("\\").append(fileinfo.name));
 32                     GetAllFiles(p.assign(path).append("\\").append(fileinfo.name), files);
 33                 }
 34             }
 35             else
 36             {
 37                 files.push_back(p.assign(path).append("\\").append(fileinfo.name));
 38             }
 39         } while (_findnext(hFile, &fileinfo) == 0);
 40         _findclose(hFile);
 41     }
 42 }
 43 
 44 //获取特定格式的文件名
 45 void GetAllFormatFiles(string path, vector<string>& files, string format)
 46 {
 47     //文件句柄
 48     long hFile = 0;
 49     //文件信息
 50     struct _finddata_t fileinfo;
 51     string p;
 52     if ((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -1)
 53     {
 54         do
 55         {
 56             if ((fileinfo.attrib & _A_SUBDIR))
 57             {
 58                 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
 59                 {
 60                     //files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
 61                     GetAllFormatFiles(p.assign(path).append("\\").append(fileinfo.name), files, format);
 62                 }
 63 
 64             }
 65             else
 66             {
 67                 files.push_back(p.assign(path).append("\\").append(fileinfo.name));
 68             }
 69         } while (_findnext(hFile, &fileinfo) == 0);
 70         _findclose(hFile);
 71     }
 72 }
 73 
 74 // 该函数有两个参数,第一个为路径字符串(string类型,最好为绝对路径);
 75 // 第二个参数为文件夹与文件名称存储变量(vector类型,引用传递)。
 76 // 在主函数中调用格式(并将结果保存在文件"AllFiles.txt"中,第一行为总数):
 77 int readfile(string filePath)
 78 {
 79     //string filePath = "testimages\\water";
 80     vector<string> files;
 81     char * distAll = "AllFiles.txt";
 82     //读取所有的文件,包括子文件的文件
 83     //GetAllFiles(filePath, files);
 84     //读取所有格式为jpg的文件
 85     string format = ".txt";
 86     GetAllFormatFiles(filePath, files, format);
 87     ofstream ofn(distAll);
 88     int size = files.size();
 89     ofn << size << endl;
 90     for (int i = 0; i < size; i++)
 91     {
 92         ofn << files[i] << endl;
 93         cout << files[i] << endl;
 94     }
 95     ofn.close();
 96     return 0;
 97 }
 98 
 99 /*************************************************************
100 方法2 不能遍历子目录
101 *************************************************************/
102 void readfile1()
103 {
104     _finddata_t file;
105     long lf;
106     //修改这里选择路径和要查找的文件类型  
107     if ((lf = _findfirst("D:\\project\\dualcamera\\TestImage\\FileTest\\c1\\s1\\*.txt*", &file)) == -1l)
108         //_findfirst返回的是long型;long __cdecl _findfirst(const char *, struct _finddata_t *)  
109         cout << "文件没有找到!\n";
110     else
111     {
112         cout << "\n文件列表:\n";
113         do {
114             cout << file.name;
115             if (file.attrib == _A_NORMAL)cout << "  普通文件  ";
116             else if (file.attrib == _A_RDONLY)cout << "  只读文件  ";
117             else if (file.attrib == _A_HIDDEN)cout << "  隐藏文件  ";
118             else if (file.attrib == _A_SYSTEM)cout << "  系统文件  ";
119             else if (file.attrib == _A_SUBDIR)cout << "  子目录  ";
120             else cout << "  存档文件  ";
121             cout << endl;
122         } while (_findnext(lf, &file) == 0);
123         //int __cdecl _findnext(long, struct _finddata_t *);如果找到下个文件的名字成功的话就返回0,否则返回-1  
124     }
125     _findclose(lf);
126 }
127 
128 
129 /*************************************************************
130 方法3 可以遍历子目录
131 *************************************************************/
132 void dir(string path)
133 {
134     long hFile = 0;
135     struct _finddata_t fileInfo;
136     string pathName, exdName;
137     // \\* 代表要遍历所有的类型
138     if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) 
139     {
140         return;
141     }
142     do
143     {
144         //判断文件的属性是文件夹还是文件
145         string  curpath = fileInfo.name;
146         if (curpath != "." && curpath != "..")
147         {
148             curpath = path + "\\" + curpath;
149             //变量文件夹中的png文件
150             if (fileInfo.attrib&_A_SUBDIR)
151             {
152                 //showfile(curpath);
153                 dir(curpath);
154             }
155             else
156             {
157                 cout << curpath << endl;
158             }
159         }
160         //cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
161     } while (_findnext(hFile, &fileInfo) == 0);
162     _findclose(hFile);
163     return;
164 }
165 
166 
167 /*************************************************************
168 方法4 先找出所有的目录和子目录,之后遍历各个目录文件
169 *************************************************************/
170 vector<string> folder;
171 void dir(string path)
172 {
173     long hFile = 0;
174     struct _finddata_t fileInfo;
175     string pathName, exdName;
176     //* 代表要遍历所有的类型
177     if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) {
178         return;
179     }
180     do
181     {
182         //判断文件的属性是文件夹还是文件
183         string  curpath = fileInfo.name;
184         if (curpath != "." && curpath != "..")
185         {
186             curpath = path + "\\" + curpath;
187             //变量文件夹中的png文件
188             if (fileInfo.attrib&_A_SUBDIR)
189             {
190                 //当前文件是目录
191                 dir(curpath);
192                 cout << curpath << endl;
193             }
194             else
195             {
196                 //进入某个子目录了
197                 cout << curpath << endl;
198             }
199         }
200         //cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
201     } while (_findnext(hFile, &fileInfo) == 0);
202     _findclose(hFile);
203     return;
204 }
205 
206 void findAllSubDir(string  srcpath)
207 {
208     _finddata_t file;
209     long lf;
210     string pathName, exdName;
211     //修改这里选择路径和要查找的文件类型  
212     if ((lf = _findfirst(pathName.assign(srcpath).append("\\*").c_str(), &file)) == -1l)
213         //_findfirst返回的是long型;long __cdecl _findfirst(const char *, struct _finddata_t *)  
214         cout << "文件没有找到!\n";
215     else
216     {
217         //cout << "\n文件列表:\n";
218         do {
219             string  curpath = file.name;
220             if (curpath != "." && curpath != "..")
221             {
222                 if (file.attrib == _A_NORMAL)cout << "  普通文件  ";
223                 else if (file.attrib == _A_RDONLY)cout << "  只读文件  ";
224                 else if (file.attrib == _A_HIDDEN)cout << "  隐藏文件  ";
225                 else if (file.attrib == _A_SYSTEM)cout << "  系统文件  ";
226                 else if (file.attrib == _A_SUBDIR)
227                 {
228                     cout << "  子目录  ";
229                     curpath = srcpath + "\\" + curpath;
230                     cout << curpath << endl;
231                     folder.push_back(curpath);
232                     //变量子目录
233                     findAllSubDir(curpath);
234                 }
235                 else
236                     ;//cout << "  存档文件  ";
237                 //cout << endl;
238             }
239         } while (_findnext(lf, &file) == 0);
240         //int __cdecl _findnext(long, struct _finddata_t *);如果找到下个文件的名字成功的话就返回0,否则返回-1  
241     }
242     _findclose(lf);
243 }
244 
245 int main()
246 {
247     //要遍历的目录
248     string path = "FileTest";
249     //dir(path);
250     findAllSubDir(path);
251     vector<string> files = folder;
252     //char * distAll = "AllFiles.txt";
253     //ofstream ofn(distAll);
254     int size = files.size();
255     //ofn << size << endl;
256     for (int i = 0; i < size; i++)
257     {
258         //ofn << files[i] << endl;
259         cout << files[i] << endl;
260         readfile(files[i]);
261     }
262     system("pause");
263     return 0;
264 }

 

 

//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[50],outfile[50];
    struct dirent *ptr;    
     DIR *dir;
    dir=opendir("./one");
    while((ptr=readdir(dir))!=NULL)
    {
  
    //跳过'.'和'..'两个目录
        if(ptr->d_name[0] == '.')
            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[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 == format) { string path = basePath; path += "/"; path += ptr->d_name; filelist.push_back(path); } } 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(filelist, base, format); } } closedir(dir); return 1; } void findDir(string src, string &dst, string filePath) { int begin = src.find(filePath) + filePath.size() + 1; int end = 0; for (int i = src.size() - 1; i >= 0; --i) { //cout << src[i] << endl; if (src[i] == '/') { end = i - 1; break; } } //cout << begin << endl; //cout << end << endl; dst = src.substr(begin, end - begin + 1); } 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 = 0; 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);  
        } } }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值