BDSIM
BDSIM is a Geant4 extension toolkit for simulation of particle transport in accelerator beamlines.
Loading...
Searching...
No Matches
BDSTemporaryFiles.cc
1/*
2Beam Delivery Simulation (BDSIM) Copyright (C) BDSIM Collaboration, 2001 - 2026.
3
4This file is part of BDSIM.
5
6BDSIM is free software: you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published
8by the Free Software Foundation version 3 of the License.
9
10BDSIM is distributed in the hope that it will be useful, but
11WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with BDSIM. If not, see <http://www.gnu.org/licenses/>.
17*/
18#include "BDSDebug.hh"
19#include "BDSException.hh"
20#include "BDSGlobalConstants.hh"
21#include "BDSTemporaryFiles.hh"
22#include "BDSUtilities.hh"
23
24#include "globals.hh"
25
26#include <cstdlib>
27#include <cstdio>
28#include <string>
29#include <sys/stat.h>
30#include <unistd.h>
31
33
35 userSpecifiedTemporaryDirectory(""),
36 temporaryDirectory(""),
37 temporaryDirectorySet(false),
38 unNamedFileCount(0)
39{
41 removeTemporaryFiles = BDSGlobalConstants::Instance()->RemoveTemporaryFiles();
42}
43
45{
46 // determine temp directory
47 std::string bdsimExecDir = BDS::GetBDSIMExecPath();
48 std::string workingDirTemp = bdsimExecDir + "temp/";
49 std::vector<G4String> dirsToTry = {"/tmp/", "/temp/", workingDirTemp};
50
51 // replace set of trial paths if one is specified explicitly in the options
53 {
54 if (userSpecifiedTemporaryDirectory.back() != '/')
57 }
58
59 for (const auto& dir : dirsToTry)
60 {
61 if (BDS::DirectoryExists(dir))
62 {// found a dir we can use - create bdsim-specific dir in it
63 // use mkdtemp, which takes template char* (non-const)
64 // use a vector for automatic clearing up with scope
65 G4String templateDir = dir + "bdsim_XXXXXX";
66 std::vector<char> v(templateDir.length() + 1);
67 std::strcpy(&v[0], templateDir.c_str());
68 char* pc = &v[0];
69
70 char* newTempDirC = mkdtemp(pc);
71 if (!newTempDirC)
72 {throw BDSException(__METHOD_NAME__, "Unable to create directory: " + templateDir);}
73 else
74 {
75 G4String newTempDir = G4String(newTempDirC);
76 temporaryDirectory = newTempDir;
77 if (temporaryDirectory.back() != '/')
78 {temporaryDirectory += "/";}
80 }
81 break;
82 }
83 }
84
85 if (!temporaryDirectorySet) // check it's ok
86 {
87 G4cerr << __METHOD_NAME__ << "Could not create temporary dir in one of:" << G4endl;
88 for (const auto& dir : dirsToTry)
89 {G4cerr << dir << G4endl;}
90 throw BDSException(__METHOD_NAME__, "Required for operation.");
91 }
92 else
93 {G4cout << __METHOD_NAME__ << "Created temporary directory in: " << temporaryDirectory << G4endl;}
94}
95
96BDSTemporaryFiles::~BDSTemporaryFiles()
97{
98 if (removeTemporaryFiles == false || (allocatedFiles.empty()))
99 {
100 // no need to warn user about deleting no files.
101 instance = nullptr;
102 return;
103 }
104
105 G4cout << __METHOD_NAME__<< "Removing temporary files" << G4endl;
106
107 for (const auto& fn : allocatedFiles)
108 {
109 if (BDS::FileExists(fn))
110 {
111#ifdef BDSDEBUG
112 G4cout << "Removing \"" << fn << "\"" << G4endl;
113#endif
114 int result = remove(fn.c_str()); // delete file
115 if (result != 0)
116#ifdef BDSDEBUG
117 {G4cout << "Error deleting file: \"" << fn << "\"" << G4endl;}
118#else
119 {continue;}
120#endif
121 }
122 }
123 // remove directory which should be empty (if not won't be deleted)
124 rmdir(temporaryDirectory);
125
126 G4cout << __METHOD_NAME__ << "Temporary files removed" << G4endl;
127}
128
135
136G4String BDSTemporaryFiles::CreateTemporaryFileUnnamed(const G4String& extension)
137{
140
141 G4String newFileName = temporaryDirectory + "bdsTemp_" + std::to_string(unNamedFileCount) + "." + extension;
142 unNamedFileCount += 1;
143
144 allocatedFiles.push_back(newFileName);
145 WarnOfNewFile(newFileName);
146 return newFileName;
147}
148
149G4String BDSTemporaryFiles::CreateTemporaryFile(const G4String& originalFilePath,
150 G4String fileNamePrefix,
151 G4String fileNameSuffix)
152{
155
156 G4String path = "";
157 G4String fileName = "";
158 BDS::SplitPathAndFileName(originalFilePath, path, fileName);
159 G4String name = "";
160 G4String extension = "";
161 BDS::SplitFileAndExtension(fileName, name, extension);
162
163 if (!fileNamePrefix.empty() && (fileNamePrefix.back() != '_'))
164 {fileNamePrefix += "_";} // ensure ends with "_" for padding
165 if (!fileNameSuffix.empty() && (fileNameSuffix.front() != '_'))
166 {fileNameSuffix = "_" + fileNameSuffix;}// ensure starts with "_" for padding
167
168 G4String newFileName = temporaryDirectory + fileNamePrefix + name + fileNameSuffix + extension;
169
170 allocatedFiles.push_back(newFileName);
171 WarnOfNewFile(newFileName);
172 return newFileName;
173}
174
175void BDSTemporaryFiles::WarnOfNewFile(const G4String& newFileName)
176{
177 G4cout << "New temporary file created: " << newFileName << G4endl;
178}
General exception with possible name of object and message.
static BDSGlobalConstants * Instance()
Access method.
Holder for all temporary files created by BDSIM.
BDSTemporaryFiles()
Private default constructor as singleton.
G4bool temporaryDirectorySet
Whether directory has been set and made.
G4bool removeTemporaryFiles
Whether to clean up.
G4String temporaryDirectory
Directory all files will be placed in.
static BDSTemporaryFiles * instance
Singleton instance.
G4int unNamedFileCount
Count of unnamed files created.
static BDSTemporaryFiles * Instance()
Singleton accessor.
G4String CreateTemporaryFileUnnamed(const G4String &extension)
std::vector< G4String > allocatedFiles
Record of of all files allocated.
G4String userSpecifiedTemporaryDirectory
Optional user-specified path to try.
G4String CreateTemporaryFile(const G4String &originalFilePath, G4String fileNamePrefix="", G4String fileNameSuffix="")
void WarnOfNewFile(const G4String &newFileName)
User feedback that new file has been created.
void SplitFileAndExtension(const G4String &fileName, G4String &file, G4String &extension)
Split a filename.ext into filename and extension. Extension includes '.'.
G4bool DirectoryExists(const G4String &path)
Check if directory exists.
G4bool FileExists(const G4String &filename)
Checks if filename exists.
void SplitPathAndFileName(const G4String &filePath, G4String &path, G4String &filename)
std::string GetBDSIMExecPath()