Skip to content

Instantly share code, notes, and snippets.

@xylcbd
Last active July 18, 2017 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xylcbd/2ea8c3bdc8213f6f5eda6b33e5a9104b to your computer and use it in GitHub Desktop.
Save xylcbd/2ea8c3bdc8213f6f5eda6b33e5a9104b to your computer and use it in GitHub Desktop.
#pragma once
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include "dirent.h"
std::string replace_all(const std::string& str, const std::string& from, const std::string& to) {
std::string result_str = str;
size_t start_pos = 0;
while ((start_pos = result_str.find(from, start_pos)) != std::string::npos) {
result_str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return result_str;
}
inline std::vector<std::string> split(const std::string& content, const std::string& delim)
{
std::vector<std::string> tokens;
std::size_t start = content.find_first_not_of(delim), end = 0;
while ((end = content.find_first_of(delim, start)) != std::string::npos)
{
tokens.push_back(content.substr(start, end - start));
start = content.find_first_not_of(delim, end);
}
if (start != std::string::npos)
tokens.push_back(content.substr(start));
return tokens;
}
inline std::string lstrip(const std::string& content, const std::string& part)
{
const std::string::size_type pos = content.find(part);
if (pos == 0)
{
return content.substr(pos, content.size() - pos);
}
return content;
}
inline std::string rstrip(const std::string& content, const std::string& part)
{
const std::string::size_type pos = content.find(part);
if (content.size() - pos == part.size())
{
return content.substr(0, pos);
}
return content;
}
inline std::string strip(const std::string& content, const std::string& part)
{
return rstrip(lstrip(content, part), part);
}
template<typename ST, typename DT>
inline DT convert(const ST x)
{
DT y;
std::stringstream ss;
ss << x;
ss >> y;
return y;
}
inline void makedir(const std::string& path)
{
std::stringstream ss;
#if _WIN32
ss << "mkdir " << replace_all(path, "/", "\\");
#else
//TODO
#endif
const std::string command = ss.str();
system(command.c_str());
}
inline std::vector<std::string> get_all_files_in_dir(const std::string& dir_path)
{
std::vector<std::string> files;
DIR *dir;
struct dirent *ent;
if ((dir = opendir(dir_path.c_str())) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (0 == strcmp(ent->d_name, ".") ||
0 == strcmp(ent->d_name, ".."))
{
continue;
}
if (ent->d_type == DT_REG)
{
files.push_back(dir_path + ent->d_name);
}
else if (ent->d_type == DT_DIR)
{
const std::vector<std::string> sub_files = get_all_files_in_dir(dir_path + ent->d_name + "\\");
std::copy(sub_files.cbegin(), sub_files.cend(), std::back_inserter(files));
}
}
closedir(dir);
}
return files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment