#include <iostream>
#include <vector>
#include <io.h>
#include <string>
using namespace std;
//遍历当前目录,不进入子文件夹
std::vector<std::string> getDirs(std::string dir)
{
std::vector<std::string> folders;
intptr_t hFile;
struct _finddata_t fileinfo;
hFile = _findfirst(dir.append("/*").c_str(), &fileinfo);
//printf("%s\n", fileinfo.name);
while (0 == _findnext(hFile, &fileinfo))
{
if (!(fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
folders.push_back(fileinfo.name);
}
}
_findclose(hFile);
return folders;
}
//遍历当前目录及其所有子目录
void getAllFiles(std::string path, std::vector<std::string>& files)
{
intptr_t hFile = 0;
struct _finddata_t fileinfo;
std::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)
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);
}
}
int main()
{
vector<string> test;
getAllFiles("E:/",test);
for(auto i = test.begin(); i!=test.end(); ++i)
{
cout << *i <<'\n';
}
return 0;
}
上述代码适用于windows.
在linux中需要适当修改,例如下面代码分解目录下所有静态库
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <vector>
bool suffix_is(const char *s, const char* suf)
{
if(s[0] == '\0') return false;
int s_len = strlen(s);
const char* dot_pos = s + (s_len - 1);
while( (*dot_pos != '.') && (dot_pos != s) ) --dot_pos;
++dot_pos;
while ((*dot_pos)!='\0')
{
if(*suf == '\0') return false;
if(*dot_pos != *suf) return false;
++dot_pos;
++suf;
}
return (*dot_pos == '\0');
}
std::vector<std::string> getFileList(std::string dir_name){
std::vector<std::string> result;
const char *dir_name_c = dir_name.c_str();
if(NULL == dir_name_c)
{
std::cout << "dir_name is null !" << std::endl;
}
struct stat s;
lstat(dir_name_c, &s);
if(!S_ISDIR(s.st_mode)){
std::cout << "dir_name is not a valid directory !" << std::endl;
return result;
}
struct dirent *filename;
DIR *dir;
dir = opendir(dir_name_c);
if(NULL == dir){
std::cout << "Can not open dir " << dir_name_c << " !" << std::endl;
return result;
}
while ((filename = readdir(dir)) != NULL)
{
std::string filePath = dir_name;
if(strcmp(filename->d_name, ".") == 0 ||
strcmp(filename->d_name, "..") == 0)
continue;
if (suffix_is(filename->d_name,"a\0"))
{
//filePath += filename->d_name;
filePath = filename->d_name;
result.push_back(filePath);
}
}
return result;
}
int main(){
auto fileList = getFileList(std::string("./"));
std::cout << fileList.size() << std::endl;
for(auto i:fileList)
{
std::cout << i << std::endl;
std::string com = "ar x " + i;
system(com.c_str());
}
return 0;
}