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;
}
好记性不如烂键盘---点滴、积累、进步!