Skip to content

Instantly share code, notes, and snippets.

@junglie85
Created August 26, 2021 07:51
Show Gist options
  • Save junglie85/803364c8b328d00c1013ea541d94b449 to your computer and use it in GitHub Desktop.
Save junglie85/803364c8b328d00c1013ea541d94b449 to your computer and use it in GitHub Desktop.
Basic C++ filesystem utility examples.
#include <filesystem>
#include <string>
namespace
{
std::string rootDirectory;
} // namespace
void triangle::fs::setRootDirectory(std::string appPath)
{
auto binDir = std::filesystem::weakly_canonical(std::filesystem::path(appPath)).parent_path();
auto rootDir = std::filesystem::weakly_canonical(binDir).parent_path();
::rootDirectory = std::string(rootDir.c_str()) + "/";
}
const std::string triangle::fs::getRootDirectory()
{
return ::rootDirectory;
}
namespace
{
std::ifstream openFile(const std::string& path)
{
std::ifstream file(path, std::ios::in);
if (!file)
{
throw std::runtime_error("triangle::assets::openFile: Cannot open file: " + path);
}
return file;
}
std::string readFile(std::ifstream file)
{
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
} // namespace
std::string triangle::assets::loadTextFile(const std::string& path)
{
auto file = ::openFile(path);
return ::readFile(std::move(file));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment