编译命令:g++ getSubFiles.cpp -std=c++11
/**************************
* File Name: getSubFiles.cpp
* Author: No One
* E-mail: 1130395634@qq.com
* Created Time: 2017-03-09 14:02:15
**************************/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
using namespace std;
void getFiles(const char* path, vector<string>& files);
int main(){
string folder = "/home/xxx/";
vector<string> files;
getFiles(folder.c_str(), files);
for_each(files.begin(), files.end(), [](const string &s){cout << s << endl; });
cout << endl;
}
void getFiles(const char* path, vector<string>& files){
const string path0 = path;
DIR* pDir;
struct dirent* ptr;
struct stat s;
lstat(path, &s);
if(!S_ISDIR(s.st_mode)){
cout << "not a valid directory: " << path << endl;
return;
}
if(!(pDir = opendir(path))){
cout << "opendir error: " << path << endl;
return;
}
int i = 0;
string subFile;
while((ptr = readdir(pDir)) != 0){
subFile = ptr -> d_name;
if(subFile == "." || subFile == "..")
continue;
subFile = path0 + subFile;
cout << ++i << ": " << subFile << endl;
files.push_back(subFile);
}
closedir(pDir);
}