Apache Mesos
mktemp.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_POSIX_MKTEMP_HPP__
14 #define __STOUT_OS_POSIX_MKTEMP_HPP__
15 
16 #include <stdlib.h>
17 #include <string.h>
18 
19 #include <string>
20 
21 #include <stout/error.hpp>
22 #include <stout/path.hpp>
23 #include <stout/try.hpp>
24 
25 #include <stout/os/close.hpp>
26 #include <stout/os/int_fd.hpp>
27 #include <stout/os/temp.hpp>
28 
29 
30 namespace os {
31 
32 // Creates a temporary file using the specified path template. The
33 // template may be any path with _6_ `Xs' appended to it, for example
34 // /tmp/temp.XXXXXX. The trailing `Xs' are replaced with a unique
35 // alphanumeric combination.
37  const std::string& path = path::join(os::temp(), "XXXXXX"))
38 {
39  char* _path = new char[path.size() + 1];
40  ::memcpy(_path, path.c_str(), path.size() + 1);
41 
42  int_fd fd = ::mkstemp(_path);
43  std::string temp(_path);
44  delete[] _path;
45 
46  if (fd < 0) {
47  return ErrnoError();
48  }
49 
51 
52  // We propagate `close` failures if creation of the temp file was successful.
53  if (close.isError()) {
54  return Error("Failed to close '" + stringify(fd) + "':" + close.error());
55  }
56 
57  return temp;
58 }
59 
60 } // namespace os {
61 
62 
63 #endif // __STOUT_OS_POSIX_MKTEMP_HPP__
Definition: path.hpp:29
Definition: errorbase.hpp:36
Definition: check.hpp:33
Try< std::string > mktemp(const std::string &path=path::join(os::temp(),"XXXXXX"))
Definition: mktemp.hpp:36
Definition: errorbase.hpp:50
Definition: posix_signalhandler.hpp:23
std::string join(const std::string &path1, const std::string &path2, const char _separator=os::PATH_SEPARATOR)
Definition: path.hpp:116
Try< Nothing > close(int fd)
Definition: close.hpp:24
static Try error(const E &e)
Definition: try.hpp:43
bool isError() const
Definition: try.hpp:78
std::string temp()
Definition: temp.hpp:27
int int_fd
Definition: int_fd.hpp:35
std::string stringify(int flags)