[C/C++]遍历目录下指定(任意)文件

来源:互联网 发布:给mac安装win7 编辑:程序博客网 时间:2024/05/18 19:46

灵活配置,可以遍历目录下指定(任意)类型文件,也可以递归遍历子目录。

直接上代码

FileScan.h

////  FileScan.h//  ftpz////  Created by 胖胖的ALEX on 2017/10/25.//#ifndef FILESCAN_H#define FILESCAN_H#include <iostream>#include <string>#include <vector>using std::string;using std::vector;class FileScan{public:/* 文件遍历初始化   @isScanSubFolder 是否遍历子目录,true是,false否   @ext 指定后缀,NULL所有文件,否则指定后缀文件   例子:   遍历所有文件,不遍历子目录  FileScan fs(false, NULL);   遍历后缀xls文件,遍历子目录  FileScan fs(true, "xls");*/FileScan(bool isScanSubFolder, char *ext);~FileScan();int scan_folder(string folder);/* 目录下所有文件 */vector<string> getFileList();private:vector<string> m_vFileList;/* true 遍历子目录; false 不遍历 */bool isScanSubFolder = false;/* 指定后缀文件,默认所有 */char *m_pExt = NULL;};#endif // !FILEMONITOR_H

FileScan.cpp

////  FileScan.cpp//  ftpz////  Created by 胖胖的ALEX on 2017/10/25.//#include "stdafx.h"#include "FileScan.h"#include <io.h>using std::fstream;using std::ios;using std::cout;using std::endl;FileScan::FileScan(bool isScanSubFolder, char *ext){this->isScanSubFolder = isScanSubFolder;this->m_pExt = ext;}FileScan::~FileScan(){this->m_vFileList.clear();this->m_pExt = NULL;}vector<string> FileScan::getFileList(){return this->m_vFileList;}int FileScan::scan_folder(string folder){// 1.check folder path exits(windows)if (_access(folder.c_str(), 0) == -1){cout << "没有这个目录" << endl;return -1;}// 2.open folderstring scanfolder = folder;intptr_t handle;_finddata_t finddata;if (m_pExt == NULL){m_pExt = "\\*.*";}else{char *c = (char*)malloc(strlen("\\*.") + strlen(m_pExt) + 1);if (c == NULL) exit(1);strcpy(c, "\\*.");strcat(c, m_pExt);m_pExt = c;}handle = _findfirst(scanfolder.append(m_pExt).c_str(), &finddata);if (handle == -1)return -1;// 3.scan file in this folderdo{if (finddata.attrib & _A_SUBDIR){if (strcmp(finddata.name, ".") == 0 || strcmp(finddata.name, "..") == 0)continue;// 在目录后面加上"\\"和搜索到的目录名进行下一次搜索if (isScanSubFolder){string inner_folder = folder;inner_folder.append("\\");inner_folder.append(finddata.name);scan_folder(inner_folder);// cout << "==" << inner_folder << endl;}}else {if (strcmp(finddata.name, "desktop.ini") == 0)continue;string curr_folder = folder;curr_folder.append("\\");curr_folder.append(finddata.name);// cout << curr_folder << endl;this->m_vFileList.push_back(curr_folder);}} while (_findnext(handle, &finddata) == 0);_findclose(handle);return 0;}

使用方法

FileScan *filescan = new FileScan(false, "zip");filescan->scan_folder("d:\\pictures");vector<string> vec = filescan->getFileList();


阅读全文
0 0
原创粉丝点击