openMSX
LocalFileReference.cc
Go to the documentation of this file.
1 #include "LocalFileReference.hh"
2 #include "File.hh"
3 #include "Filename.hh"
4 #include "FileOperations.hh"
5 #include "FileException.hh"
6 #include "build-info.hh"
7 #include <cstdio>
8 #include <cassert>
9 
10 using std::string;
11 
12 namespace openmsx {
13 
15 {
16  init(file);
17 }
18 
20 {
21  File file(filename);
22  init(file);
23 }
24 
26  : LocalFileReference(filename.getResolved())
27 {
28 }
29 
30 void LocalFileReference::init(File& file)
31 {
32  tmpFile = file.getLocalReference();
33  if (!tmpFile.empty()) {
34  // file is backed on the (local) filesystem,
35  // we can simply use the path to that file
36  assert(tmpDir.empty()); // no need to delete file/dir later
37  return;
38  }
39 
40  // create temp dir
41 #if defined(_WIN32) || PLATFORM_ANDROID
43 #else
44  // TODO - why not just use getTempDir()?
45  tmpDir = strCat("/tmp/openmsx.", int(getpid()));
46 #endif
47  // it's possible this directory already exists, in that case the
48  // following function does nothing
49  FileOperations::mkdirp(tmpDir);
50 
51  // create temp file
52  auto fp = FileOperations::openUniqueFile(tmpDir, tmpFile);
53  if (!fp) {
54  throw FileException("Couldn't create temp file");
55  }
56 
57  // write temp file
58  auto mmap = file.mmap();
59  if (fwrite(mmap.data(), 1, mmap.size(), fp.get()) != mmap.size()) {
60  throw FileException("Couldn't write temp file");
61  }
62 }
63 
65 {
66  if (!tmpDir.empty()) {
67  FileOperations::unlink(tmpFile);
68  // it's possible the directory is not empty, in that case
69  // the following function will fail, we ignore that error
70  FileOperations::rmdir(tmpDir);
71  }
72 }
73 
74 const string& LocalFileReference::getFilename() const
75 {
76  assert(!tmpFile.empty());
77  return tmpFile;
78 }
79 
80 } // namespace openmsx
int unlink(const std::string &path)
Call unlink() in a platform-independent manner.
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.
constexpr const char *const filename
This class represents a filename.
Definition: Filename.hh:17
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
int rmdir(const std::string &path)
Call rmdir() in a platform-independent manner.
string getTempDir()
Get the name of the temp directory on the system.
void mkdirp(string_view path_)
std::string strCat(Ts &&...ts)
Definition: strCat.hh:573
span< uint8_t > mmap()
Map file in memory.
Definition: File.cc:93
Helper class to use files in APIs other than openmsx::File.