Commit f21c2b4e authored by Paul Asmuth's avatar Paul Asmuth
Browse files

FileOutputStream#openFile

parent abdbd092
Loading
Loading
Loading
Loading

build/tests/.gitignore

0 → 100644
+1 −0
Original line number Diff line number Diff line
tmp
+0 −0

Empty file added.

+2 −1
Original line number Diff line number Diff line
@@ -979,7 +979,8 @@ TEST_CASE(QueryTest, TestQueryService, [] () {

  QueryService query_service;
  auto input = fnordmetric::util::StringInputStream::fromString(query);
  auto output = fnordmetric::util::OutputStream::getStdout();
  auto output = fnordmetric::util::FileOutputStream::openFile(
      "build/tests/tmp/QueryTest_TestQueryService_out.svg");

  query_service.executeQuery(
      input.get(),
+27 −0
Original line number Diff line number Diff line
@@ -4,9 +4,12 @@
 *
 * Licensed under the MIT license (see LICENSE).
 */
#include <fcntl.h>
#include <memory>
#include <string>
#include <unistd.h>
#include <fnordmetric/util/outputstream.h>
#include <fnordmetric/util/runtimeexception.h>

namespace fnordmetric {
namespace util {
@@ -21,6 +24,30 @@ std::unique_ptr<OutputStream> OutputStream::getStderr() {
  return std::unique_ptr<OutputStream>(stderr_stream);
}

std::unique_ptr<FileOutputStream> FileOutputStream::openFile(
    const std::string& file_path,
    int flags /* = O_CREAT | O_TRUNC */,
    int permissions /* = 0666 */) {
  int fd = -1;
  auto fp = file_path.c_str();

  flags |= O_WRONLY;

  if ((flags & O_CREAT) == O_CREAT) {
    fd = open(fp, flags, permissions);
  } else {
    fd = open(fp, flags);
  }

  if (fd < 1) {
    RAISE_ERRNO(RuntimeException, "error opening file '%s'", fp);
  }

  return std::unique_ptr<FileOutputStream>(new FileOutputStream(fd, true));
}



FileOutputStream::FileOutputStream(
    int fd,
    bool close_on_destroy /* = false */) :
+14 −0
Original line number Diff line number Diff line
@@ -6,6 +6,7 @@
 */
#ifndef _FNORDMETRIC_OUTPUTSTREAM_H
#define _FNORDMETRIC_OUTPUTSTREAM_H
#include <fcntl.h>
#include <memory>

namespace fnordmetric {
@@ -42,6 +43,19 @@ public:
class FileOutputStream : public OutputStream {
public:

  /**
   * Create a new FileOutputStream instance by opening the provided file for
   * writing. The fille will automatically be close()ed when the output stream
   * is destroyed.
   *
   * @param file_path the path to the file to open
   * @param flags flags to pass to the open() syscall
   */
  static std::unique_ptr<FileOutputStream> openFile(
      const std::string& file_path,
      int flags = O_CREAT | O_TRUNC,
      int permissions = 0666);

  /**
   * Create a new FileOuputStream instance from the provided filedescriptor. If 
   * close on_destroy is true, the fd will be close()ed when the output stream