Apache Mesos
ls.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_LS_HPP__
14 #define __STOUT_OS_POSIX_LS_HPP__
15 
16 #include <dirent.h>
17 #include <errno.h>
18 #include <stdlib.h>
19 
20 #include <list>
21 #include <string>
22 
23 #include <stout/error.hpp>
24 #include <stout/try.hpp>
25 
26 
27 namespace os {
28 
29 inline Try<std::list<std::string>> ls(const std::string& directory)
30 {
31  DIR* dir = opendir(directory.c_str());
32 
33  if (dir == nullptr) {
34  return ErrnoError("Failed to opendir '" + directory + "'");
35  }
36 
37  std::list<std::string> result;
38  struct dirent* entry;
39 
40  // Zero `errno` before starting to call `readdir`. This is necessary
41  // to allow us to determine when `readdir` returns an error.
42  errno = 0;
43 
44  while ((entry = readdir(dir)) != nullptr) {
45  if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
46  continue;
47  }
48  result.push_back(entry->d_name);
49  }
50 
51  if (errno != 0) {
52  // Preserve `readdir` error.
53  Error error = ErrnoError("Failed to read directory");
54  closedir(dir);
55  return error;
56  }
57 
58  if (closedir(dir) == -1) {
59  return ErrnoError("Failed to close directory");
60  }
61 
62  return result;
63 }
64 
65 } // namespace os {
66 
67 #endif // __STOUT_OS_POSIX_LS_HPP__
Definition: errorbase.hpp:35
Definition: try.hpp:34
Definition: errorbase.hpp:49
std::string error(const std::string &msg, uint32_t code)
Try< std::list< std::string > > ls(const std::string &directory)
Definition: ls.hpp:29