首页 > 代码库 > C++ 递归读取目录下所有文件

C++ 递归读取目录下所有文件

windows版本

#include <iostream>#include <io.h>#include <fstream>#include <string>#include <sstream>using namespace std;void getAllFiles(string path, vector<string>& files){    //文件句柄      long   hFile = 0;    //文件信息      struct _finddata_t fileinfo;  //很少用的文件信息读取结构    string p;  //string类很有意思的一个赋值函数:assign(),有很多重载版本    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);  //寻找下一个,成功返回0,否则-1        _findclose(hFile);    }}int main(){    char * inPath = "./srcImg";    vector<string> files;    //测试    char * distAll = "AllFiles.txt";    getAllFiles(inPath, files);    ofstream ofn(distAll);    int size = files.size();    ofn << size << endl;    for (int i = 0; i<size; i++)    {    ofn << files[i] << endl;    }    ofn.close();    return 0;}

 

linux版本

#include <iostream>#include <string>#include <iostream>#include <string>#include <vector>#include <fstream>extern "C"{    #include <sys/types.h>    #include <sys/stat.h>    #include <unistd.h>    #include <errno.h>    #include <dirent.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>}using namespace std;void getAllFiles(string path, vector<string>& files){    DIR *dir;    struct dirent *ptr;    if((dir=opendir(path.c_str()))==NULL){        perror("Open dri error...");        exit(1);    }    while((ptr=readdir(dir))!=NULL){        if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0)            continue;        else if(ptr->d_type==8)//file            files.push_back(path+"/"+ptr->d_name);        else if(ptr->d_type==10)//link file            continue;        else if(ptr->d_type==4){            //files.push_back(ptr->d_name);//dir            getAllFiles(path+"/"+ptr->d_name,files);        }    }    closedir(dir);}int main(int argc,char **argv){    if(argc<2){        cout<<"USAGE:./a.out path"<<endl;        exit(-1);    }    char * filePath = argv[1];    vector<string> files;    char * distAll = "allFiles.txt";    getAllFiles(filePath, files);    ofstream ofn(distAll);    int size = files.size();    //ofn << size << endl;    for (int i = 0; i<size; i++)    {        ofn << files[i] << endl;    }    ofn.close();    return 0;}

 

C++ 递归读取目录下所有文件