OpenVPN 3 Core Library
Loading...
Searching...
No Matches
enumdir.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#ifndef OPENVPN_COMMON_ENUMDIR_H
13#define OPENVPN_COMMON_ENUMDIR_H
14
15#include <sys/types.h>
16#include <dirent.h>
17
18#include <string>
19#include <vector>
20#include <utility>
21#include <memory>
22#include <algorithm>
23#include <functional>
24
28
29namespace openvpn {
30OPENVPN_EXCEPTION(enum_dir_error);
31
32template <typename F>
33inline bool enum_dir(const std::string &dirname,
34 F func)
35{
36 unique_ptr_del<DIR> dir(::opendir(dirname.c_str()), [](DIR *d)
37 { ::closedir(d); });
38 if (!dir)
39 return false;
40
41 struct dirent *e;
42 while ((e = ::readdir(dir.get())) != nullptr)
43 {
44 std::string fn(e->d_name);
45 if (fn != "." && fn != "..")
46 std::invoke(func, std::move(fn));
47 }
48 return true;
49}
50
51inline std::vector<std::string> enum_dir(const std::string &dirname,
52 const size_t size_hint = 0,
53 const bool sort = false)
54{
55 std::vector<std::string> ret;
56 if (size_hint)
57 ret.reserve(size_hint);
58
59 if (!enum_dir(dirname, [&ret](std::string fn)
60 { ret.push_back(std::move(fn)); }))
61 throw enum_dir_error(dirname + ": cannot open directory");
62
63 if (sort)
64 std::sort(ret.begin(), ret.end());
65
66 return ret;
67}
68
69} // namespace openvpn
70
71#endif
#define OPENVPN_EXCEPTION(C)
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
bool enum_dir(const std::string &dirname, F func)
Definition enumdir.hpp:33
std::unique_ptr< T, std::function< void(T *)> > unique_ptr_del
Definition uniqueptr.hpp:21
std::string ret
void dirname(const std::string &path)
Definition test_path.cpp:18