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* temp = new char[path.size() + 1];
40  ::memcpy(temp, path.c_str(), path.size() + 1);
41 
42  int_fd fd = ::mkstemp(temp);
43  if (fd < 0) {
44  delete[] temp;
45  return ErrnoError();
46  }
47 
48  // We ignore the return value of close(). This is because users
49  // calling this function are interested in the return value of
50  // mkstemp(). Also an unsuccessful close() doesn't affect the file.
51  os::close(fd);
52 
53  std::string result(temp);
54  delete[] temp;
55  return result;
56 }
57 
58 } // namespace os {
59 
60 
61 #endif // __STOUT_OS_POSIX_MKTEMP_HPP__
Definition: path.hpp:26
Definition: check.hpp:33
Try< std::string > mktemp(const std::string &path=path::join(os::temp(),"XXXXXX"))
Definition: mktemp.hpp:36
Definition: errorbase.hpp:49
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:56
Try< Nothing > close(int fd)
Definition: close.hpp:24
std::string temp()
Definition: temp.hpp:27
int int_fd
Definition: int_fd.hpp:35