From cd14d68c47e9d6528e1ed52db782ddd8ed43969d Mon Sep 17 00:00:00 2001 From: Carl Pearson Date: Wed, 25 Sep 2019 09:56:57 -0500 Subject: [PATCH] check for existance using stat --- include/perfect/detail/fs.hpp | 17 ++++++++++++++-- include/perfect/detail/fs/linux.hpp | 31 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 include/perfect/detail/fs/linux.hpp diff --git a/include/perfect/detail/fs.hpp b/include/perfect/detail/fs.hpp index 891d699..a9e1ac2 100644 --- a/include/perfect/detail/fs.hpp +++ b/include/perfect/detail/fs.hpp @@ -3,15 +3,28 @@ #include #include -#include "perfect/result.hpp" +#include "../result.hpp" + +#ifdef __linux__ +#include "fs/linux.hpp" +#else +#error "unsupported platform" +#endif namespace perfect { namespace detail { + Result write_str(const std::string &path, const std::string &val) { + + if (!path_exists(path)) { + std::cerr << "write_str(): does not exist: " << path << "\n"; + return Result::NOT_SUPPORTED; + } + std::ofstream ofs(path); if (ofs.fail()) { std::cerr << "failed to open " << path << "\n"; - return Result::NOT_SUPPORTED; + return Result::NO_PERMISSION; } ofs << val; diff --git a/include/perfect/detail/fs/linux.hpp b/include/perfect/detail/fs/linux.hpp new file mode 100644 index 0000000..27cc2f9 --- /dev/null +++ b/include/perfect/detail/fs/linux.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include +#include + + + +#include +#include +#include + +namespace perfect { + namespace detail { + bool path_exists(const std::string &path) { + struct stat sb; + if (stat(path.c_str(), &sb)) { + switch (errno) { + case ENOENT: return false; + case ENOTDIR: return false; + default: { + std::cerr << "unhandled error in stat() for " << path << "\n"; + assert(0); + } + } + } + return true; + } + } +} \ No newline at end of file