File conditionalfilestream.h
File List > code_source > templat > include > TempLat > util > conditionaloutput > conditionalfilestream.h
Go to the documentation of this file
#ifndef TEMPLAT_UTIL_CONDITIONALOUTPUT_CONDITIONALFILESTREAM_H
#define TEMPLAT_UTIL_CONDITIONALOUTPUT_CONDITIONALFILESTREAM_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 <fstream>
#include "TempLat/util/exception.h"
#include "TempLat/util/conditionaloutput/conditionalstream.h"
namespace TempLat
{
MakeException(ConditionalFileStreamError);
class ConditionalFileStream : public ConditionalStream
{
public:
// Put public methods here. These should change very little over time.
ConditionalFileStream(const std::string &fname_, bool enabled_, std::ios_base::openmode mode = std::ios_base::out)
: ConditionalStream(stream, enabled_), fname(fname_), mMode(mode)
{
if (enabled_) {
Enable();
}
}
~ConditionalFileStream()
{
if (stream.is_open()) stream.close();
}
void Enable()
{
if (!stream.is_open()) stream.open(fname, mMode);
if (!stream.is_open()) throw ConditionalFileStreamError("Could not open \"" + fname + "\"");
}
friend std::ostream &operator<<(std::ostream &ostream, const ConditionalFileStream &obj)
{
ostream << "File(" << obj.fname << ")";
if (!obj.stream.is_open()) ostream << " (disabled)";
return ostream;
}
std::ostream &flush() { return stream.flush(); }
private:
/* Put all member variables and private methods here. These may change arbitrarily. */
std::ofstream stream;
std::string fname;
std::ios_base::openmode mMode;
};
} // namespace TempLat
#endif