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); }
相关文章推荐
- 使用C++获取文件夹中所有文件名(windows环境)
- 使用C++获取文件夹中所有文件名(windows环境)
- c++利用windows api遍历指定文件夹及其子文件夹中的文件
- 使用C++获取文件夹中所有文件名(windows环境)
- java io 使用递归删除指定的文件夹及其子文件夹和文件 先测试再正式使用哦
- c++利用windows api遍历指定文件夹及其子文件夹中的文件
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- 获取文件夹及其子文件夹下的文件名
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- [转]Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- linux 删除所有文件夹下指定文件名的文件
- 非递归遍历指定文件夹下的所有文件及其子文件夹 [11/29/2010 更新]
- 使用ps命令获取Linux环境下全部RAC集群进程信息
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境
- 使用某个文件夹下的所有文件去替换另一个文件夹下及其子文件夹下存在的同名文件(Python实现)
- Ubuntu(Linux)使用Eclipse搭建C/C++编译环境