| 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 | /* Workaround for _LARGE_FILES and _LARGE_FILE_API incompatibility on AIX */ |
| 13 | #if defined(_AIX) && defined(_LARGE_FILE_API) |
| 14 | #undef _LARGE_FILE_API |
| 15 | #endif |
| 16 | |
| 17 | #include <unistd.h> |
| 18 | #include <sys/types.h> |
| 19 | #include <dirent.h> |
| 20 | #include <stdio.h> |
| 21 | |
| 22 | #include "util.hpp" |
| 23 | |
| 24 | namespace dena { |
| 25 | |
| 26 | struct auto_file : private noncopyable { |
| 27 | auto_file() : fd(-1) { } |
| 28 | ~auto_file() { |
| 29 | reset(); |
| 30 | } |
| 31 | int get() const { return fd; } |
| 32 | int close() { |
| 33 | if (fd < 0) { |
| 34 | return 0; |
| 35 | } |
| 36 | const int r = ::close(fd); |
| 37 | fd = -1; |
| 38 | return r; |
| 39 | } |
| 40 | void reset(int x = -1) { |
| 41 | if (fd >= 0) { |
| 42 | this->close(); |
| 43 | } |
| 44 | fd = x; |
| 45 | } |
| 46 | private: |
| 47 | int fd; |
| 48 | }; |
| 49 | |
| 50 | struct auto_dir : private noncopyable { |
| 51 | auto_dir() : dp(0) { } |
| 52 | ~auto_dir() { |
| 53 | reset(); |
| 54 | } |
| 55 | DIR *get() const { return dp; } |
| 56 | void reset(DIR *d = 0) { |
| 57 | if (dp != 0) { |
| 58 | closedir(dp); |
| 59 | } |
| 60 | dp = d; |
| 61 | } |
| 62 | private: |
| 63 | DIR *dp; |
| 64 | }; |
| 65 | |
| 66 | }; |
| 67 | |
| 68 | #endif |
| 69 | |
| 70 | |