C++獲取目錄下的檔案
阿新 • • 發佈:2018-12-21
程式碼:
#include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> #include <iostream> #include <string> #include <vector> using namespace std; void ScanDir(const std::string path, std::vector<std::string> &files) { DIR *dir; struct dirent *ptr; dir = opendir(path.c_str()); ///open the dir while((ptr = readdir(dir)) != NULL) ///read the list of this dir { files.push_back(ptr->d_name); } closedir(dir); } void PrintFiles(const vector<std::string> &files) { cout << "當前目錄下有" << files.size() << "個檔案,它們是:" << endl; for(auto i = files.cbegin(); i != files.cend(); ++i) { cout << *i << endl; } } int main(int argc, char **argv) { std::string path; std::vector<std::string> files; if(argc >= 2) { path = std::string(argv[1]); } else { path = std::string("./"); } ScanDir(path, files); PrintFiles(files); return 0; }