diff options
author | Adrian Kummerlaender | 2015-10-18 17:19:55 +0200 |
---|---|---|
committer | Adrian Kummerlaender | 2015-10-18 17:19:55 +0200 |
commit | ceb01fb33a039d4f315c9aa9217320be44cefa2d (patch) | |
tree | e7e651184c69b7f300ddbc7780d8ece436e4346c /io.h | |
parent | f057a3e9116539cd96916cfd8fb790cf6a87de79 (diff) | |
download | change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.tar change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.tar.gz change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.tar.bz2 change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.tar.lz change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.tar.xz change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.tar.zst change-ceb01fb33a039d4f315c9aa9217320be44cefa2d.zip |
Move io and logging functionality into separate namespaces
Diffstat (limited to 'io.h')
-rw-r--r-- | io.h | 54 |
1 files changed, 54 insertions, 0 deletions
@@ -0,0 +1,54 @@ +#ifndef CHANGE_IO_H_ +#define CHANGE_IO_H_ + +#include <unistd.h> +#include <dlfcn.h> +#include <fcntl.h> +#include <sys/stat.h> + +#include <cstring> + +namespace io { + +struct FileDescriptorGuard { + FileDescriptorGuard(const std::string& path) { + this->fd = open(path.c_str(), O_WRONLY | O_APPEND); + + if ( !this->fd ) { + this->fd = STDERR_FILENO; + } + } + + ~FileDescriptorGuard() { + close(this->fd); + } + + 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); +} + +} + +#endif // CHANGE_IO_H_ |