c++ 小函数

1. ubuntu c++ 获取文件夹以及子文件夹下所有文件目录

#include <dirent.h>
#include <vector>

std::vector<std::string> GetFiles(const std::string& sdir = ".",
                                  bool bsubdir = true) {
    DIR* dp;
    struct dirent* dirp;
    std::vector<std::string> filenames;
    if ((dp = opendir(sdir.c_str())) != NULL) {
        while ((dirp = readdir(dp)) != NULL) {
            if (strcmp(".", dirp->d_name) == 0 || strcmp("..", dirp->d_name) == 0)
                continue;
            if (dirp->d_type != DT_DIR)
                filenames.push_back(sdir + "/" + dirp->d_name);
            if (bsubdir && dirp->d_type == DT_DIR) {
                std::vector<std::string> names = GetFiles(sdir + "/" + dirp->d_name);
                filenames.insert(filenames.begin(), names.begin(), names.end());
            }
        }
    }
    closedir(dp);
    return filenames;
}

2. str_replace

string str_replace(const string &str,const string &str_find,const string &str_replacee)
{
    string str_tmp=str;
    size_t pos = str_tmp.find(str_find);
    while (pos != string::npos)
    {
        str_tmp.replace(pos, str_find.length(), str_replacee);

        size_t pos_t=pos+str_replacee.length();
        string str_sub=str_tmp.substr(pos_t,str_tmp.length()-pos_t);

        size_t pos_tt=str_sub.find(str_find);
        if(string::npos != pos_tt)
        {
            pos =pos_t + str_sub.find(str_find);
        }else
        {
            pos=string::npos;
        }
    }
    return str_tmp;
}
posted @ 2023-05-05 10:55  无左无右  阅读(12)  评论(0编辑  收藏  举报