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
13namespace {
14Mantid::Kernel::Logger logger("ScopedFileHelper");
15}
16
17namespace ScopedFileHelper {
21ScopedFile::ScopedFile(const std::string &fileContents, const std::string &fileName) {
22 Poco::Path path(Mantid::Kernel::ConfigService::Instance().getTempDir().c_str());
23 path.append(fileName);
24 doCreateFile(fileContents, path);
25}
26
30ScopedFile::ScopedFile(const std::string &fileContents, const std::string &fileName, const std::string &fileDirectory) {
31 Poco::Path path(fileDirectory);
32 path.append(fileName);
33 doCreateFile(fileContents, path);
34}
35
39void ScopedFile::release() const { this->m_filename.clear(); }
40
43 if (this != &other) {
44 this->m_file.close();
45 this->m_filename = other.m_filename;
46 other.release();
47 }
48 return *this;
49}
50
53 this->m_filename = other.m_filename;
54 other.release();
55}
56
61void ScopedFile::doCreateFile(const std::string &fileContents, const Poco::Path &fileNameAndPath) {
62 m_filename = fileNameAndPath.toString();
63 m_file.open(m_filename.c_str(), std::ios_base::out);
64 if (!m_file.is_open()) {
65 throw std::runtime_error("Cannot open " + m_filename);
66 }
67 m_file << fileContents;
68 m_file.close();
69}
70
75std::string ScopedFile::getFileName() const { return m_filename; }
76
79 if (!m_filename.empty()) // check that file should be disposed.
80 {
81 m_file.close();
82 if (remove(m_filename.c_str()) != 0) {
83 // destructors shouldn't throw exceptions so we have to resort to printing
84 // an error
85 logger.error() << "~ScopedFile() - Error deleting file '" << m_filename << "'\n";
86 }
87 }
88}
89} // namespace ScopedFileHelper
The Logger class is in charge of the publishing messages from the framework through various channels.
Definition: Logger.h:52
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
std::string getFileName() const
Getter for the filename with path.
ScopedFile(const std::string &fileContents, const std::string &fileName)
Constructor generates the file.
ScopedFile & operator=(const ScopedFile &other)
Assignement.
void doCreateFile(const std::string &fileContents, const Poco::Path &fileNameAndPath)
Common method used by all constructors.
void release() const
Release the resource from management.
~ScopedFile()
Free up resources.