Mantid
Loading...
Searching...
No Matches
ScopedFileHelper.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7//------------------------------------------------------------------------------
8// Includes
9//------------------------------------------------------------------------------
11#include "MantidKernel/Logger.h"
12
13#include <filesystem>
14
15namespace {
16Mantid::Kernel::Logger logger("ScopedFileHelper");
17}
18
19namespace ScopedFileHelper {
23ScopedFile::ScopedFile(const std::string &fileContents, const std::string &fileName) {
24 std::filesystem::path path(Mantid::Kernel::ConfigService::Instance().getTempDir().c_str());
25 path /= fileName;
26 doCreateFile(fileContents, path);
27}
28
32ScopedFile::ScopedFile(const std::string &fileContents, const std::string &fileName, const std::string &fileDirectory) {
33 std::filesystem::path path(fileDirectory);
34 path /= fileName;
35 doCreateFile(fileContents, path);
36}
37
41void ScopedFile::release() const { this->m_filename.clear(); }
42
45 if (this != &other) {
46 this->m_file.close();
47 this->m_filename = other.m_filename;
48 other.release();
49 }
50 return *this;
51}
52
55 this->m_filename = other.m_filename;
56 other.release();
57}
58
63void ScopedFile::doCreateFile(const std::string &fileContents, const std::filesystem::path &fileNameAndPath) {
64 m_filename = fileNameAndPath.string();
65 m_file.open(m_filename.c_str(), std::ios_base::out);
66 if (!m_file.is_open()) {
67 throw std::runtime_error("Cannot open " + m_filename);
68 }
69 m_file << fileContents;
70 m_file.close();
71}
72
77const std::string &ScopedFile::getFileName() const { return m_filename; }
78
81 if (!m_filename.empty()) // check that file should be disposed.
82 {
83 m_file.close();
84 if (remove(m_filename.c_str()) != 0) {
85 // destructors shouldn't throw exceptions so we have to resort to printing
86 // an error
87 logger.error() << "~ScopedFile() - Error deleting file '" << m_filename << "'\n";
88 }
89 }
90}
91} // namespace ScopedFileHelper
The Logger class is in charge of the publishing messages from the framework through various channels.
Definition Logger.h:51
ScopedFile(const std::string &fileContents, const std::string &fileName)
Constructor generates the file.
ScopedFile & operator=(const ScopedFile &other)
Assignement.
void release() const
Release the resource from management.
const std::string & getFileName() const
Getter for the filename with path.
void doCreateFile(const std::string &fileContents, const std::filesystem::path &fileNameAndPath)
Common method used by all constructors.