check for existance using stat

This commit is contained in:
Carl Pearson
2019-09-25 09:56:57 -05:00
parent 2e32089786
commit cd14d68c47
2 changed files with 46 additions and 2 deletions

View File

@@ -3,15 +3,28 @@
#include <fstream>
#include <string>
#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;

View File

@@ -0,0 +1,31 @@
#pragma once
#include <string>
#include <cerrno>
#include <iostream>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
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;
}
}
}