file.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // C++ interface for POSIX files-related syscalls
  2. //
  3. // Platform: ISO C++ 98/11 - POSIX
  4. // $Id$
  5. //
  6. // (c) __vic 2012
  7. #ifndef __VIC_POSIX_FILE_H
  8. #define __VIC_POSIX_FILE_H
  9. #include<__vic/defs.h>
  10. #include __VIC_SWAP_HEADER
  11. #include<sys/types.h>
  12. #include<unistd.h>
  13. #include<fcntl.h>
  14. namespace __vic { namespace posix {
  15. //////////////////////////////////////////////////////////////////////////////
  16. // RAII-wrapper for file descriptor
  17. class file : private non_copyable
  18. {
  19. int fd;
  20. public:
  21. explicit __VIC_CONSTEXPR_FUNC file(int fd = -1) : fd(fd) {}
  22. file(const char *name, int flags, ::mode_t mode = 0666)
  23. : fd(::open(name, flags, mode)) {}
  24. ~file() { if(is_open()) close_nt(fd); }
  25. #if __cpp_rvalue_references
  26. file(file &&o) noexcept : fd(o.fd) { o.fd = -1; }
  27. file &operator=(file &&o) noexcept { swap(o); return *this; }
  28. #endif
  29. bool open(const char *name, int flags, ::mode_t mode = 0666)
  30. { fd = ::open(name, flags, mode); return is_open(); }
  31. bool is_open() const { return fd >= 0; }
  32. void close() { close_reset(fd); }
  33. bool close_nt() noexcept { bool st = close_nt(fd); fd = -1; return st; }
  34. void swap(file &o) noexcept { std::swap(fd, o.fd); }
  35. int attach_handle(int f) { int old = fd; fd = f; return old; }
  36. int detach_handle() { return attach_handle(-1); }
  37. int handle() const { return fd; }
  38. int descriptor() const { return handle(); }
  39. size_t read_max(void *buf, size_t n) { return read_max(fd, buf, n); }
  40. size_t read_some(void *buf, size_t n) { return read_some(fd, buf, n); }
  41. void write_all(const void *buf, size_t n) { write_all(fd, buf, n); }
  42. size_t write_all_nt(const void *buf, size_t n) noexcept
  43. { return write_all_nt(fd, buf, n); }
  44. static size_t read_max(int , void * , size_t );
  45. static size_t read_some(int , void * , size_t );
  46. static void write_all(int , const void * , size_t );
  47. static size_t write_all_nt(int , const void * , size_t ) noexcept;
  48. static void close_reset(int & );
  49. static bool close_nt(int ) noexcept;
  50. };
  51. //////////////////////////////////////////////////////////////////////////////
  52. }} // namespace
  53. #endif // header guard