aboutsummaryrefslogtreecommitdiff
path: root/src/utility/io.h
diff options
context:
space:
mode:
authorAdrian Kummerlaender2015-12-24 00:11:06 +0100
committerAdrian Kummerlaender2015-12-24 00:11:06 +0100
commitbaf30b7b83822b7d6efd0c16761b8e42a1e96101 (patch)
tree33eebf92abdde2f2cfbba138bb506529a332955e /src/utility/io.h
parentcce63aca270c51fb3ce9790438e3c23864de0a87 (diff)
downloadchange-baf30b7b83822b7d6efd0c16761b8e42a1e96101.tar
change-baf30b7b83822b7d6efd0c16761b8e42a1e96101.tar.gz
change-baf30b7b83822b7d6efd0c16761b8e42a1e96101.tar.bz2
change-baf30b7b83822b7d6efd0c16761b8e42a1e96101.tar.lz
change-baf30b7b83822b7d6efd0c16761b8e42a1e96101.tar.xz
change-baf30b7b83822b7d6efd0c16761b8e42a1e96101.tar.zst
change-baf30b7b83822b7d6efd0c16761b8e42a1e96101.zip
Match namespace and directory structure
Diffstat (limited to 'src/utility/io.h')
-rw-r--r--src/utility/io.h68
1 files changed, 68 insertions, 0 deletions
diff --git a/src/utility/io.h b/src/utility/io.h
new file mode 100644
index 0000000..ed1f542
--- /dev/null
+++ b/src/utility/io.h
@@ -0,0 +1,68 @@
+#ifndef CHANGE_SRC_UTILITY_IO_H_
+#define CHANGE_SRC_UTILITY_IO_H_
+
+#include <unistd.h>
+#include <dlfcn.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+#include <cstring>
+
+namespace utility {
+
+class FileDescriptorGuard {
+ public:
+ FileDescriptorGuard(const std::string& path) {
+ this->fd_ = open(path.c_str(), O_CREAT | O_WRONLY | O_APPEND);
+
+ if ( !this->fd_ ) {
+ this->fd_ = STDERR_FILENO;
+ }
+ }
+
+ ~FileDescriptorGuard() {
+ close(this->fd_);
+ }
+
+ operator int() {
+ return this->fd_;
+ }
+
+ private:
+ int fd_;
+
+};
+
+std::string get_file_name(int fd) {
+ char proc_link[20];
+ char file_name[256];
+
+ snprintf(proc_link, sizeof(proc_link), "/proc/self/fd/%d", fd);
+ const ssize_t name_size = readlink(proc_link, file_name, sizeof(file_name));
+
+ if ( name_size > 0 ) {
+ file_name[name_size] = '\0';
+
+ return std::string(file_name);
+ } else {
+ return std::string();
+ }
+}
+
+bool is_regular_file(int fd) {
+ struct stat fd_stat;
+ fstat(fd, &fd_stat);
+
+ return S_ISREG(fd_stat.st_mode);
+}
+
+bool is_regular_file(const char* path) {
+ struct stat fd_stat;
+ lstat(path, &fd_stat);
+
+ return S_ISREG(fd_stat.st_mode);
+}
+
+}
+
+#endif // CHANGE_SRC_UTILITY_IO_H_