CBMC
tempdir.cpp
Go to the documentation of this file.
1 /*******************************************************************\
2 
3 Module:
4 
5 Author: CM Wintersteiger
6 
7 \*******************************************************************/
8 
9 #include "tempdir.h"
10 
11 #include <filesystem>
12 
13 // clang-format off
14 #ifndef _WIN32
15 #if defined(__FreeBSD_kernel__) || \
16  defined(__CYGWIN__) || \
17  defined(__MACH__)
18 #include <unistd.h>
19 #endif
20 
21 #include <cstdlib>
22 #include <cstring>
23 #include <vector>
24 #endif
25 // clang-format on
26 
27 #include "exception_utils.h"
28 
29 std::string get_temporary_directory(const std::string &name_template)
30 {
31  std::string result;
32 
33 #ifdef _WIN32
34  (void)name_template; // unused parameter
35  try
36  {
37  result = std::filesystem::temp_directory_path().string();
38  }
39  catch(const std::filesystem::filesystem_error &)
40  {
41  throw system_exceptiont("Failed to create temporary directory");
42  }
43 #else
44  std::string prefixed_name_template = "/tmp/";
45  const char *TMPDIR_env = getenv("TMPDIR");
46  if(TMPDIR_env != nullptr)
47  prefixed_name_template = TMPDIR_env;
48  if(*prefixed_name_template.rbegin() != '/')
49  prefixed_name_template += '/';
50  prefixed_name_template += name_template;
51 
52  std::vector<char> t(
53  prefixed_name_template.begin(), prefixed_name_template.end());
54  t.push_back('\0'); // add the zero
55  const char *td = mkdtemp(t.data());
56  if(!td)
57  throw system_exceptiont("Failed to create temporary directory");
58 
59  errno = 0;
60  char *wd = realpath(td, nullptr);
61 
62  if(wd == nullptr)
63  throw system_exceptiont(
64  std::string("realpath failed: ") + std::strerror(errno));
65 
66  result = std::string(wd);
67  free(wd);
68 #endif
69 
70  return result;
71 }
72 
73 temp_dirt::temp_dirt(const std::string &name_template)
74 {
75  path=get_temporary_directory(name_template);
76 }
77 
78 std::string temp_dirt::operator()(const std::string &file)
79 {
80  return std::filesystem::path(path).append(file).string();
81 }
82 
84 {
85  std::filesystem::remove_all(path);
86 }
87 
89 {
90  clear();
91 }
Thrown when some external system fails unexpectedly.
~temp_dirt()
Definition: tempdir.cpp:88
temp_dirt(const std::string &name_template)
Definition: tempdir.cpp:73
std::string operator()(const std::string &file)
Definition: tempdir.cpp:78
std::string path
Definition: tempdir.h:36
void clear()
Definition: tempdir.cpp:83
char * getenv(const char *name)
Definition: stdlib.c:496
void free(void *ptr)
Definition: stdlib.c:317
char * strerror(int errnum)
Definition: string.c:1014
std::string get_temporary_directory(const std::string &name_template)
Definition: tempdir.cpp:29