Search code examples
cfiletreedirectory-walk

Porting Java NIO Files.walkFileTree visitor to C, maintaining thread-safety


I have some existing Java code that uses java.nio.file.Files.walkFileTree with the FileVisitor interface, but now I need to port it to plain C. Is there a C equivalent of this interface? If not, what primitives can I use to build one?

I've looked at the Unix ftw and nftw functions, but it doesn't appear that they will work because the callback function doesn't have a parameter for supplying user variables (a single void* param would have been nice). My code needs to be thread-safe.


Solution

  • I already had this need of file walking for one of my project. I also needed it to be portable on Linux and Windows.

    I did not found an open source implementation for it and finally ended up implementing it myself. This was finally not too much work.

    On the Linux side, I used opendir() and readdir() to iterate over directory entries.
    On the Windows side, I used FindFirstFileA() and FindNextFileA() to do the job.
    Next for each entry, I simply call a used defined callback.

    Both implementations does not take much than 100 lines of code... So I would suggest you to DIY.