aboutsummaryrefslogtreecommitdiff
path: root/riscv/log_file.h
blob: 9e210bba028ab178e44fbc3e61ffe6f1f1e7fc7e (plain)
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
// See LICENSE for license details.
#ifndef _RISCV_LOGFILE_H
#define _RISCV_LOGFILE_H

#include <stdio.h>
#include <memory>
#include <sstream>
#include <stdexcept>

// Header-only class wrapping a log file. When constructed with an
// actual path, it opens the named file for writing. When constructed
// with the null path, it wraps stderr.
class log_file_t
{
public:
  log_file_t(const char *path)
    : wrapped_file (nullptr, &fclose)
  {
    if (!path)
      return;

    wrapped_file.reset(fopen(path, "w"));
    if (! wrapped_file) {
      std::ostringstream oss;
      oss << "Failed to open log file at `" << path << "': "
          << strerror (errno);
      throw std::runtime_error(oss.str());
    }
  }

  FILE *get() { return wrapped_file ? wrapped_file.get() : stderr; }

private:
  std::unique_ptr<FILE, int(*)(FILE*)> wrapped_file;
};

#endif