天天看點

ubuntu c++ 周遊檔案

編譯指令:g++ getSubFiles.cpp -std=c++11

/**************************  
 * File Name: getSubFiles.cpp
 * Author: No One  
 * E-mail: [email protected]  
 * 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 = ;
    string subFile;
    while((ptr = readdir(pDir)) != ){
        subFile = ptr -> d_name;
        if(subFile == "." || subFile == "..")
            continue;
        subFile = path0 + subFile;
        cout << ++i << ": " << subFile << endl;
        files.push_back(subFile);
    }
    closedir(pDir);

}

           

繼續閱讀