10 #ifndef SUPPORTLIB_FILESYSTEM_H
11 #define SUPPORTLIB_FILESYSTEM_H
25 namespace FileSystem {
34 using SPtr = std::shared_ptr<FileSystemException>;
35 using UPtr = std::unique_ptr<FileSystemException>;
36 using WPtr = std::weak_ptr<FileSystemException>;
44 inline std::vector<char>
LoadFile(
const std::filesystem::path& file) {
45 if(!std::filesystem::exists(file))
49 in.open(file, std::ios::in | std::ios::binary);
53 in.seekg(0, in.end);
size_t len = in.tellg(); in.seekg(0, in.beg);
54 std::vector<char> b(len);
55 in.read((
char*)&b[0], len);
68 inline bool WriteFile(
const std::filesystem::path& file,
const std::vector<char>& data)
71 out.open(file, std::ios::out | std::ios::binary);
74 out.write((
char*)&data[0], data.size() *
sizeof(
char));
85 std::string path = getenv(
"PATH");
91 std::vector<std::string> tokens;
93 std::istringstream tokenStream(path);
94 while (std::getline(tokenStream, token, delim))
96 std::filesystem::path exec(token);
97 exec.append(executable);
98 if(std::filesystem::exists(exec))
100 exec.replace_extension(
".exe");
101 if(std::filesystem::exists(exec))
112 std::array<char, 128> buffer;
115 std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cmd.c_str(),
"r"), _pclose);
117 std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(),
"r"), pclose);
122 while (fgets(buffer.data(), buffer.size(), pipe.get()) !=
nullptr) {
123 result += buffer.data();
133 inline std::future<void>
ExecuteAsync(
const std::string& cmd, std::ostream& ostr = std::cout) {
134 auto hdl = std::async(std::launch::async, [&] {
136 std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cmd.c_str(),
"r"), _pclose);
138 std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(),
"r"), pclose);
143 std::array<char, 128> buffer;
144 while (fgets(buffer.data(), buffer.size(), pipe.get()) !=
nullptr) {
145 ostr << buffer.data();
Base exception to inherit custom exceptions from.
Base exception to inherit custom exceptions from.
Definition: Exception.h:48
ExceptionBase(const std::string &msg="")
Definition: Exception.h:54
Exception to be thrown on FileSystem errors.
Definition: FileSystem.h:31
std::vector< char > LoadFile(const std::filesystem::path &file)
Definition: FileSystem.h:44
std::string ExecuteSync(const std::string &cmd)
Definition: FileSystem.h:111
std::future< void > ExecuteAsync(const std::string &cmd, std::ostream &ostr=std::cout)
Definition: FileSystem.h:133
bool WriteFile(const std::filesystem::path &file, const std::vector< char > &data)
Definition: FileSystem.h:68
std::filesystem::path FindExecutableInPath(const std::string &executable)
Definition: FileSystem.h:83
Namespace for giri's C++ support library.
Definition: Base64.h:47