您的位置:首页 > 运维架构 > Linux

Linux 环境下使用C++ 提取指定文件夹及其子文件夹中的文件名信息

2017-03-12 21:12 477 查看
1. 关键是#include <dirent.h>头文件中包含的一些关于文件操作的属性。可以将文件夹及子文件夹中的文件信息提取出来保存在vector<string>中

/*
环境: LInux
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <iostream>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;
//文件夹下文件信息及其子文件夹中的文件信息
void listDir(const char *name, vector<string> &fileNames, bool lastSlash);
int main()
{
string directoryPath="/root/testDir/";
vector<string> fileNames;
listDir(directoryPath.c_str(),fileNames,true);

cout<<"total files: "<<fileNames.size()<<endl;
cout<<fileNames[0]<<endl;
return 0;
}
void listDir(const char *name, vector<string> &fileNames, bool lastSlash)
{
DIR *dir;
struct dirent *entry;
struct stat statbuf;
struct tm      *tm;
time_t rawtime;
if (!(dir = opendir(name)))
{
cout<<"Couldn't open the file or dir"<<name<<"\n";
return;
}
if (!(entry = readdir(dir)))
{
cout<<"Couldn't read the file or dir"<<name<<"\n";
return;
}

do
{
string slash="";
if(!lastSlash)
slash = "/";

string parent(name);
string file(entry->d_name);
string final = parent + slash + file;
if(stat(final.c_str(), &statbuf)==-1)
{
cout<<"Couldn't get the stat info of file or dir: "<<final<<"\n";
return;
}
if (entry->d_type == DT_DIR) //its a directory
{
//skip the . and .. directory
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
listDir(final.c_str(), fileNames, false);
}
else // it is a file
{
fileNames.push_back(final);
}
}while (entry = readdir(dir));
closedir(dir);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: