File: ScopedFileOutputStream.h

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (82 lines) | stat: -rw-r--r-- 1,722 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#pragma once

#include <memory>
#include <fstream>
#include <string>
#include <cassert>
#include "util/Noncopyable.h"

namespace stream
{

/**
 * Helper class wrapping around a std::ofstream. The instance can be empty,
 * until a filename is been passed to it.
 *
 * If there is a contained stream, it is ensured that it is 
 * closed when the instance is destroyed.
 * 
 * The underlying stream can be accessed through the dereference operator*()
 */
class ScopedOutputStream :
    public std::ofstream
{
private:
    std::unique_ptr<std::ofstream> _stream;

public:
    // Constructs an empty stream object, no stream is opened
    // until the open() method is invoked
    ScopedFileOutputStream()
    {}

    // Constructs the wrapper and opens the internal stream
    // using the given filename
    ScopedFileOutputStream(const std::string& filename)
	{
        open(filename);
    }

    ~ScopedFileOutputStream()
    {
        if (_stream)
        {
            _stream->flush();
            _stream->close();
            _stream.reset();
        }
    }

    // Returns true if there's no underlying stream object instantiated
    bool isEmpty() const
    {
        return static_cast<bool>(_stream);
    }

    bool isOpen() const
    {
        return _stream && _stream->is_open();
    }

    std::ostream& operator*()
    {
        assert(_stream);
        return *_stream;
    }

    const std::ostream& operator*() const
    {
        assert(_stream);
        return *_stream;
    }

    // Open the internal stream using the given filename
    void open(const std::string& filename)
    {
        assert(!_stream); // no duplicate open calls

        _stream.reset(new std::ofstream(filename));
    }
};

}