dirop

来源:互联网 发布:手机游戏变速软件 编辑:程序博客网 时间:2024/06/01 10:07
/****************************************************************************@File Name: DirOp.h@Author: wangzhicheng@mail: 2363702560@qq.com@Created Time: Fri 10 Feb 2017 01:31:34 PM CST****************************************************************************/#ifndef DIR_OP_H#define DIR_OP_H#include <stdio.h>#include <dirent.h>#include <string.h>#include <sys/stat.h>#include <string>#include <vector>#include <algorithm>#include <thread>namespace dirop{using namespace std;class DirOp{private:string m_strDirPath;// absolute pathpublic:DirOp(const string &path):m_strDirPath(path){}/* * @brief get all the file paths in the dir  * */void GetFilePaths(vector<string>&paths);private:/* * @brief get all the file paths in the dir  * */void GetFilePaths(const char *path, vector<string>&paths);};}#endif/****************************************************************************@File Name: DirOp.cpp@Author: wangzhicheng@mail: 2363702560@qq.com@Created Time: Fri 10 Feb 2017 01:31:34 PM CST****************************************************************************/#include "DirOp.h"namespace dirop{/* * @brief get all the file paths in the dir  * */void DirOp::GetFilePaths(vector<string>&paths){GetFilePaths(m_strDirPath.c_str(), paths);}/* * @brief get all the file paths in the dir  * */void DirOp::GetFilePaths(const char *path, vector<string>&paths){DIR *dp = nullptr;struct dirent *dirp = nullptr;struct stat st;string newpath;static const string STR = "/"; if(!(dp = opendir(path))) {closedir(dp);dp = nullptr;fprintf(stderr, "%s can not be open...!", path);return;}while((dirp = readdir(dp))) {if(!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, "..")) continue;// generate a new pathnewpath = path;if('/' != newpath[newpath.size() - 1]) newpath += STR;// judge the last characternewpath += dirp->d_name;// stat the pathif(stat(newpath.c_str(), &st)){fprintf(stderr, "%s can not be stated...!\n", newpath.c_str());continue;}// is directoryif(S_ISDIR(st.st_mode)){GetFilePaths(newpath.c_str(), paths);}else{paths.emplace_back(newpath);// performance loss vector<string>&paths> -> string paths separated by blank character/*static const string STR = " ";char buf[256] = {0};string str;//memcpy(buf, newpath.c_str(), newpath.size());copy(begin(newpath), end(newpath), begin(str));str += STR;paths += str;*/}}closedir(dp);}}/****************************************************************************@File Name: test.cpp@Author: wangzhicheng@mail: wangzhicheng@qq.com@Created Time: Fri 10 Feb 2017 02:04:46 PM CST****************************************************************************/#include <iostream>#include <algorithm>#include "DirOp.h"using namespace dirop;int main(){vector<string>paths;DirOp dirop("/home");dirop.GetFilePaths(paths);for_each(begin(paths), end(paths), [](const string &path){cout << path << endl;});return 0;}

0 0
原创粉丝点击