Apache Mesos
mkdir.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_MKDIR_HPP__
14 #define __STOUT_OS_POSIX_MKDIR_HPP__
15 
16 #include <sys/stat.h>
17 
18 #include <string>
19 #include <vector>
20 
21 #include <stout/error.hpp>
22 #include <stout/nothing.hpp>
23 #include <stout/strings.hpp>
24 #include <stout/try.hpp>
25 
26 #include <stout/os/constants.hpp>
27 
28 
29 namespace os {
30 
31 inline Try<Nothing> mkdir(const std::string& directory, bool recursive = true)
32 {
33  if (!recursive) {
34  if (::mkdir(directory.c_str(), 0755) < 0) {
35  return ErrnoError();
36  }
37  } else {
38  std::vector<std::string> tokens =
40 
41  std::string path;
42 
43  // We got an absolute path, so keep the leading slash.
44  if (directory.find_first_of(stringify(os::PATH_SEPARATOR)) == 0) {
45  path = os::PATH_SEPARATOR;
46  }
47 
48  foreach (const std::string& token, tokens) {
49  path += token;
50  if (::mkdir(path.c_str(), 0755) < 0 && errno != EEXIST) {
51  return ErrnoError();
52  }
53 
54  path += os::PATH_SEPARATOR;
55  }
56  }
57 
58  return Nothing();
59 }
60 
61 } // namespace os {
62 
63 #endif // __STOUT_OS_POSIX_MKDIR_HPP__
Definition: nothing.hpp:16
Definition: try.hpp:34
Definition: errorbase.hpp:49
std::vector< std::string > tokenize(const std::string &s, const std::string &delims, const Option< size_t > &maxTokens=None())
Definition: strings.hpp:138
Try< Nothing > mkdir(const std::string &directory, bool recursive=true)
Definition: mkdir.hpp:31
std::string stringify(int flags)
constexpr char PATH_SEPARATOR
Definition: constants.hpp:24