check for existance using stat
This commit is contained in:
@@ -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;
|
||||
|
31
include/perfect/detail/fs/linux.hpp
Normal file
31
include/perfect/detail/fs/linux.hpp
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user