Skip to content

File namedtmpfile.h

File List > code_source > templat > include > TempLat > util > namedtmpfile.h

Go to the documentation of this file

#ifndef TEMPLAT_UTIL_NAMEDTMPFILE_H
#define TEMPLAT_UTIL_NAMEDTMPFILE_H

/* This file is part of TempLat, available at https://cosmolattice.github.io/templat .
   Copyright 2021-2026 The TempLat authors, see AUTHORS.md.
   Released under the MIT license, see LICENSE.md. */

// File info: Main contributor(s): Wessel Valkenburg, Year: 2019

#include <iostream>
#include <cstdio>
#include <string>
#include <fstream>

namespace TempLat
{

  class NamedTmpFile
  {
  public:
    // Put public methods here. These should change very little over time.
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
    NamedTmpFile()
        : // # removing the deprecation warning here, because the security issue is not an issue for us, this class is
          // for development and testing, not for production.
          name(std::tmpnam(NULL)), outfile(name)
    {
    }

    NamedTmpFile(std::string presetName) : name(presetName), outfile(name) {}

    ~NamedTmpFile() { close(); }

    const std::string &getName() { return name; }

    template <typename T> NamedTmpFile &operator<<(const T &obj)
    {
      outfile << obj;
      return *this;
    }

    int remove()
    {
      close();
      return std::remove(name.c_str());
    }

    void close()
    {
      if (outfile.is_open()) outfile.close();
    }

  private:
    /* Put all member variables and private methods here. These may change arbitrarily. */
    std::string name;
    std::ofstream outfile;
    friend struct NamedTmpFileTester;
  };
} // namespace TempLat
#endif