openMSX
LocalFileReference.cc
Go to the documentation of this file.
2
3#include "File.hh"
4#include "Filename.hh"
5#include "FileOperations.hh"
6#include "FileException.hh"
7
8#include "build-info.hh"
9
10#include <cstdio>
11#include <cassert>
12
13namespace openmsx {
14
16{
17 init(file);
18}
19
21{
22 File file(std::move(filename));
23 init(file);
24}
25
27 : LocalFileReference(filename.getResolved())
28{
29}
30
32 : LocalFileReference(std::move(filename).getResolved())
33{
34}
35
37 : tmpFile(std::move(other.tmpFile))
38 , tmpDir (std::move(other.tmpDir ))
39{
40 other.tmpDir.clear();
41}
42
44{
45 cleanup();
46 tmpFile = std::move(other.tmpFile);
47 tmpDir = std::move(other.tmpDir);
48 other.tmpDir.clear();
49 return *this;
50}
51
56
57void LocalFileReference::init(File& file)
58{
59 tmpFile = file.getLocalReference();
60 if (!tmpFile.empty()) {
61 // file is backed on the (local) filesystem,
62 // we can simply use the path to that file
63 assert(tmpDir.empty()); // no need to delete file/dir later
64 return;
65 }
66
67 // create temp dir
68#if defined(_WIN32) || PLATFORM_ANDROID
70#else
71 // TODO - why not just use getTempDir()?
72 tmpDir = strCat("/tmp/openmsx.", int(getpid()));
73#endif
74 // it's possible this directory already exists, in that case the
75 // following function does nothing
77
78 // create temp file
79 auto fp = FileOperations::openUniqueFile(tmpDir, tmpFile);
80 if (!fp) {
81 throw FileException("Couldn't create temp file");
82 }
83
84 // write temp file
85 auto mmap = file.mmap();
86 if (fwrite(mmap.data(), 1, mmap.size(), fp.get()) != mmap.size()) {
87 throw FileException("Couldn't write temp file");
88 }
89}
90
91void LocalFileReference::cleanup() const
92{
93 if (!tmpDir.empty()) {
95 // it's possible the directory is not empty, in that case
96 // the following function will fail, we ignore that error
98 }
99}
100
101const std::string& LocalFileReference::getFilename() const
102{
103 assert(!tmpFile.empty());
104 return tmpFile;
105}
106
107} // namespace openmsx
std::span< const uint8_t > mmap()
Map file in memory.
Definition File.cc:102
This class represents a filename.
Definition Filename.hh:20
Helper class to use files in APIs other than openmsx::File.
LocalFileReference & operator=(const LocalFileReference &)=delete
const std::string & getFilename() const
Returns path to a local uncompressed version of this file.
FILE_t openUniqueFile(const std::string &directory, std::string &filename)
Open a new file with a unique name in the provided directory.
int rmdir(zstring_view path)
Call rmdir() in a platform-independent manner.
string getTempDir()
Get the name of the temp directory on the system.
void mkdirp(string path)
Acts like the unix command "mkdir -p".
int unlink(zstring_view path)
Call unlink() in a platform-independent manner.
This file implemented 3 utility functions:
Definition Autofire.cc:11
STL namespace.
std::string strCat()
Definition strCat.hh:703