From 5012f2e5827ef664407adb7fc503cda3da046f88 Mon Sep 17 00:00:00 2001 From: Bob Polis Date: Sat, 25 Apr 2020 17:42:26 +0200 Subject: [PATCH] made all fdstreams RAII for fd --- fdstream.cpp | 28 ++++++++++++++++++++++++++++ libscio.hpp | 6 ++++++ sciotest/main.cpp | 3 --- 3 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 fdstream.cpp diff --git a/fdstream.cpp b/fdstream.cpp new file mode 100644 index 0000000..b977e34 --- /dev/null +++ b/fdstream.cpp @@ -0,0 +1,28 @@ +// +// fdstream.cpp +// libscio +// +// Created by Bob Polis at 2020-04-25 +// Copyright (c) 2020 SwiftCoder. All rights reserved. +// + +#include "libscio.hpp" +#include + +sc::io::fdostream::~fdostream() { + if (_outbuf.fd() != -1) { + ::close(_outbuf.fd()); + } +} + +sc::io::fdistream::~fdistream() { + if (_inbuf.fd() != -1) { + ::close(_inbuf.fd()); + } +} + +sc::io::fdstream::~fdstream() { + if (_iobuf.fd() != -1) { + ::close(_iobuf.fd()); + } +} diff --git a/libscio.hpp b/libscio.hpp index e5ce3a1..c5ffbe1 100644 --- a/libscio.hpp +++ b/libscio.hpp @@ -56,6 +56,8 @@ namespace sc { fdostream(int fd) : std::ostream(&_outbuf), _outbuf(fd) {} fdostream() : std::ostream(&_outbuf), _outbuf(-1) {} + virtual ~fdostream(); + int fd() const { return _outbuf.fd(); } void fd(int fd) { _outbuf.fd(fd); } @@ -68,6 +70,8 @@ namespace sc { fdistream(int fd) : std::istream(&_inbuf), _inbuf(fd) {} fdistream() : std::istream(&_inbuf), _inbuf(-1) {} + virtual ~fdistream(); + int fd() const { return _inbuf.fd(); } void fd(int fd) { _inbuf.fd(fd); } @@ -80,6 +84,8 @@ namespace sc { fdstream() : std::iostream(&_iobuf) {} fdstream(int fd) : std::iostream(&_iobuf), _iobuf(fd) {} + virtual ~fdstream(); + int fd() const { return _iobuf.fd(); } void fd(int fd) { _iobuf.fd(fd); } diff --git a/sciotest/main.cpp b/sciotest/main.cpp index 1ad3533..97c93a6 100644 --- a/sciotest/main.cpp +++ b/sciotest/main.cpp @@ -66,7 +66,6 @@ void test3() { throw_if_min1(fd = ::open("passwd", mode, perm)); sc::io::fdostream os {fd}; os << passwd; - throw_if_min1(::close(fd)); } void test4() { @@ -77,7 +76,6 @@ void test4() { while (getline(is, line)) { cout << line << '\n'; } - throw_if_min1(::close(fd)); } void test5() { @@ -92,7 +90,6 @@ void test5() { if (getline(file, line)) { cout << line << '\n'; } - throw_if_min1(::close(fd)); } int main(int argc, const char * argv[]) {