| 1 |
#include "main.ih" |
| 2 |
|
| 3 |
|
| 4 |
inline bool accept(DirEntry const &entry) |
| 5 |
{ |
| 6 |
return entry.d_name != "."s and entry.d_name != ".."s; |
| 7 |
} |
| 8 |
|
| 9 |
// yield all `DirEntry`s contained in the particular `path` (as long as it |
| 10 |
// is a directory) |
| 11 |
|
| 12 |
// if (not dirPtr) |
| 13 |
// co_return; |
| 14 |
// removed from 'dirEntries' after calling opendir: like Dir, let's assume |
| 15 |
// that the demo allows us to assume that opendir succeeds. |
| 16 |
|
| 17 |
//+dir |
| 18 |
Generator<DirEntry> dirEntries(char const *path) |
| 19 |
{ |
| 20 |
DIR *dirPtr = opendir(path); |
| 21 |
|
| 22 |
while (auto entry = readdir(dirPtr)) |
| 23 |
{ |
| 24 |
if (accept(*entry)) |
| 25 |
co_yield *entry; |
| 26 |
} |
| 27 |
closedir(dirPtr); |
| 28 |
} |
| 29 |
//+dir |
| 30 |
|
| 31 |
// keep track of the _full_ path rather than only the entry's own name |
| 32 |
//+path |
| 33 |
Generator<Pair> dirPathEntries(char const *path) |
| 34 |
{ |
| 35 |
for (auto const &entry: dirEntries(path)) |
| 36 |
co_yield make_pair(entry, |
| 37 |
(string{path} + '/' + entry.d_name).c_str()); |
| 38 |
} |
| 39 |
//+path |
| 40 |
|
| 41 |
// Recursively visit the directory tree: |
| 42 |
// yield all entries in the current directory and if an entry is |
| 43 |
// a directory, recursively handle that directory |
| 44 |
//+allentries |
| 45 |
RecursiveGenerator<Pair> visitAllEntries(char const *path) |
| 46 |
{ |
| 47 |
for (auto &entry_pair: dirPathEntries(path)) |
| 48 |
{ |
| 49 |
co_yield entry_pair; |
| 50 |
|
| 51 |
auto [entry, entry_path] = entry_pair; |
| 52 |
if (entry.d_type == DT_DIR) |
| 53 |
co_yield visitAllEntries(entry_path); |
| 54 |
} |
| 55 |
} |
| 56 |
//+allentries |
| 57 |
|
| 58 |
// Run this program with a directory path as single argument |
| 59 |
// (it defaults to `.`, i.e., the current directory). |
| 60 |
// It (recursively lists all files and directories in that directory |
| 61 |
//main |
| 62 |
int main(int argc, char **argv) |
| 63 |
{ |
| 64 |
char const *path = argc == 1 ? "." : argv[1]; |
| 65 |
|
| 66 |
for (auto [entry, entryPath ]: visitAllEntries(path)) |
| 67 |
cout << entryPath << '\n'; |
| 68 |
} |
| 69 |
//= |