Today I’m going to talk about recursively walking a directory in c++.

I wanted to tackle this using experimental c++17 (or c++xy, because coroutines were not included in the standard), and so what came to mind was the generator pattern, bearing similarity to python’s os.walk.

Luckily, msvc has brought us some cool tricks, like co-routines and other c++17 goodies.

So, first thing’s first, I thought about the interface I’d like to provide – my aim was to get similar results to the python equivalent:

Considering that, my return type should include:

The root directory The subdirectories The files within that directory

For that purpose, I have defined a “WalkEntry” (hopefully we’ll see structure bindings in the future):

Given WalkEntry, the walk function should consider:

The root path Following symlinks Yielding a WalkEntry

I have ended up with the following implementation:

You can see that I haven’t simply traversed with the directory iterator, and instead used do-while – the reason for this is that I wanted to include the root path in the result set, as that what we see in os.walk.

* I should mention that I have used vs15 update 1, if you’re using vs15 update 2, you should probably replace __yield_value with co_return

So now our usage looks like this:

And the output:

Conclusions

Generators are neat and are easily implementable with yield support.

We won’t see them in c++17, but they are pushed to a TS, so that’s promising.

Here’s a link so you can play with the code online:

https://github.com/dany74q/cppxy-dir-walk

Enjoy!