ALPSCore reference
unique_file.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1998-2018 ALPS Collaboration. See COPYRIGHT.TXT
3  * All rights reserved. Use is subject to license terms. See LICENSE.TXT
4  * For use in publications, see ACKNOWLEDGE.TXT
5  */
6 
7 
9 #include <cstdlib>
10 #include <cstdio>
11 #include <vector>
12 #include <stdexcept>
13 
14 // excerpt from <unistd.h>
15 extern "C" int close(int);
16 
17 namespace alps {
18  namespace testing {
19 
27  unique_file::unique_file(const std::string& prefix, unique_file::action_type action) : action_(action)
28  {
29  // We need a modifiable 0-terminated char buffer
30  std::vector<char> strbuf(prefix.begin(), prefix.end());
31  strbuf.insert(strbuf.end(), 7, 'X');
32  strbuf.back()='\0';
33 
34  int fd=mkstemp(&strbuf[0]);
35  if (fd==-1) {
36  throw std::runtime_error("Failed to generate a temporary name from template '"
37  + std::string(&strbuf[0]) + "'");
38  }
39  close(fd);
40  name_.assign(&strbuf[0]);
41  if (REMOVE_NOW==action || REMOVE_AND_DISOWN==action) std::remove(&strbuf[0]);
42  }
43 
45  if (REMOVE_AFTER==action_ || REMOVE_NOW==action_) {
46  remove(name_.c_str()); // we ignore removal failure
47  }
48  }
49 
50  }
51 }
~unique_file()
Closes and optionally deletes the file.
Definition: unique_file.cpp:44
unique_file(const std::string &prefix, action_type action=KEEP_AFTER)
Generates a random file name with a given prefix.
Definition: unique_file.cpp:27
Remove the file when destroying the object.
Definition: unique_file.hpp:20
int close(int)
Remove the file after constructing the object only.
Definition: unique_file.hpp:23
Remove the file after constructing the object, remove when destructing too.
Definition: unique_file.hpp:22