1 2 // vim:sw=2:ai 3 4 /* 5 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved. 6 * See COPYRIGHT.txt for details. 7 */ 8 9 #ifndef DENA_AUTO_FILE_HPP 10 #define DENA_AUTO_FILE_HPP 11 12 #include <unistd.h> 13 #include <sys/types.h> 14 #include <dirent.h> 15 #include <stdio.h> 16 17 #include "util.hpp" 18 19 namespace dena { 20 21 struct auto_file : private noncopyable { auto_filedena::auto_file22 auto_file() : fd(-1) { } ~auto_filedena::auto_file23 ~auto_file() { 24 reset(); 25 } getdena::auto_file26 int get() const { return fd; } closedena::auto_file27 int close() { 28 if (fd < 0) { 29 return 0; 30 } 31 const int r = ::close(fd); 32 fd = -1; 33 return r; 34 } resetdena::auto_file35 void reset(int x = -1) { 36 if (fd >= 0) { 37 this->close(); 38 } 39 fd = x; 40 } 41 private: 42 int fd; 43 }; 44 45 struct auto_dir : private noncopyable { auto_dirdena::auto_dir46 auto_dir() : dp(0) { } ~auto_dirdena::auto_dir47 ~auto_dir() { 48 reset(); 49 } getdena::auto_dir50 DIR *get() const { return dp; } resetdena::auto_dir51 void reset(DIR *d = 0) { 52 if (dp != 0) { 53 closedir(dp); 54 } 55 dp = d; 56 } 57 private: 58 DIR *dp; 59 }; 60 61 }; 62 63 #endif 64 65