From 7ce74ce206065c3af0035583330b3c773086f21c Mon Sep 17 00:00:00 2001 From: Karen Arutyunov Date: Thu, 3 Nov 2016 00:44:53 +0300 Subject: Invent auto_fd, make use of it in fdstreams and process --- butl/fdstream.ixx | 64 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 20 deletions(-) (limited to 'butl/fdstream.ixx') diff --git a/butl/fdstream.ixx b/butl/fdstream.ixx index c7c329b..5d38d36 100644 --- a/butl/fdstream.ixx +++ b/butl/fdstream.ixx @@ -6,26 +6,51 @@ namespace butl { - // ifdstream + // auto_fd // - inline ifdstream:: - ifdstream () - : std::istream (&buf_) + inline auto_fd& auto_fd:: + operator= (auto_fd&& fd) noexcept + { + reset (fd.release ()); + return *this; + } + + inline int auto_fd:: + release () noexcept { - exceptions (badbit | failbit); + int r (fd_); + fd_ = -1; + return r; } + inline void auto_fd:: + reset (int fd) noexcept + { + if (fd_ >= 0) + fdclose (fd_); // Don't check for an error as not much we can do here. + + fd_ = fd; + } + + // ifdstream + // inline ifdstream:: - ifdstream (int fd, iostate e) - : fdstream_base (fd), std::istream (&buf_) + ifdstream (auto_fd&& fd, iostate e) + : fdstream_base (std::move (fd)), std::istream (&buf_) { assert (e & badbit); exceptions (e); } inline ifdstream:: - ifdstream (int fd, fdstream_mode m, iostate e) - : fdstream_base (fd, m), + ifdstream (iostate e) + : ifdstream (auto_fd (), e) // Delegate. + { + } + + inline ifdstream:: + ifdstream (auto_fd&& fd, fdstream_mode m, iostate e) + : fdstream_base (std::move (fd), m), std::istream (&buf_), skip_ ((m & fdstream_mode::skip) == fdstream_mode::skip) { @@ -84,23 +109,22 @@ namespace butl // ofdstream // inline ofdstream:: - ofdstream () - : std::ostream (&buf_) + ofdstream (auto_fd&& fd, iostate e) + : fdstream_base (std::move (fd)), std::ostream (&buf_) { - exceptions (badbit | failbit); + assert (e & badbit); + exceptions (e); } inline ofdstream:: - ofdstream (int fd, iostate e) - : fdstream_base (fd), std::ostream (&buf_) + ofdstream (iostate e) + : ofdstream (auto_fd (), e) // Delegate. { - assert (e & badbit); - exceptions (e); } inline ofdstream:: - ofdstream (int fd, fdstream_mode m, iostate e) - : fdstream_base (fd, m), std::ostream (&buf_) + ofdstream (auto_fd&& fd, fdstream_mode m, iostate e) + : fdstream_base (std::move (fd), m), std::ostream (&buf_) { assert (e & badbit); exceptions (e); @@ -156,13 +180,13 @@ namespace butl // fdopen() // - inline int + inline auto_fd fdopen (const std::string& f, fdopen_mode m, permissions p) { return fdopen (f.c_str (), m, p); } - inline int + inline auto_fd fdopen (const path& f, fdopen_mode m, permissions p) { return fdopen (f.string (), m, p); -- cgit v1.1