ubutnu C++获取所有文件

#include <iostream>
#include <vector>
#include <dirent.h>
#include <sys/stat.h>

using namespace std;

int findfileinfolder(const char *dir_name, string extend_name, vector<string> &file_names) {
    int number = 0;
    // check the parameter !
    if( NULL == dir_name ) {
        cout << " dir_name is null ! " << endl;
        return 0;
    }
    // check if dir_name is a valid directory
    struct stat s;
    lstat( dir_name , &s );

    DIR *dir = opendir( dir_name );
    if( NULL == dir ) {
        cout<<"Can not open dir "<<dir_name<<endl;
        return 0;
    }
    /* read all the files in the dir ~ */
    struct dirent *filename;
    while( ( filename = readdir(dir) ) != NULL ) {
        // get rid of "." and ".."
        if( strcmp( filename->d_name , "." ) == 0 ||
            strcmp( filename->d_name , "..") == 0    )
            continue;
        //获取文件后缀
        string sFilename(filename->d_name);
        string suffixStr = sFilename.substr(sFilename.find_last_of('.') + 1);
        //根据后缀筛选文件
        if (suffixStr.compare(extend_name) == 0) {
            cout<<sFilename <<endl;
            file_names.push_back(sFilename);
            ++number;
        }
    }
    return number;
}

int main(int argc, char **argv) {
    vector<string> file_names;
    findfileinfolder("/home/ubuntu/Pictures", "png", file_names);
    cout << "first: " << file_names[0] << endl;
    cout << file_names.size() << endl;
    return 0;
}
发布了50 篇原创文章 · 获赞 31 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/random_repick/article/details/102687822