可直接使用,修改自其它博客,侵删
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
using namespace std;
void List(const char *path, int level, vector<string> &strvec)
{
struct dirent* ent = NULL;
DIR *pDir;
pDir = opendir(path);
if (pDir == NULL)
{
return;
}
while (NULL != (ent = readdir(pDir)))
{
if (ent->d_type == 8)
{
//file
strvec.push_back(ent->d_name);
}
else
{
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
{
continue;
}
//directory
string _path(path);
string _dirName(ent->d_name);
string fullDirPath = _path + "/" + _dirName;
List(fullDirPath.c_str(), level + 1, strvec);
}
}
}
int main()
{
char path[256];
vector<string> file_list;
cin>>path;
List(path, 0, file_list);
vector<string>::iterator file_entry = file_list.begin();
for(; file_entry != file_list.end(); ++file_entry)
{
cout<<*file_entry<<endl;
}
return 0;
}