Question

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.

Était-ce utile?

La 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.

Autres conseils

Both the BSD operating systems and Linux supply a family of function called fts(3), that do the same thing as POSIX ftw but without the inversion of control via callbacks. Instead, the paradigm is that you "open" an FS hierarchy to get a handle, then "read" entries out of that:

char *const roots[] = {root, NULL};  // fts allows for multiple roots
FTS *hier = fts_open(roots, FTS_PHYSICAL | FTS_NOSTAT, NULL);
FTSENT *entry;

while ((entry = fts_read(hier)) != NULL) {
    puts(entry->fts_path);
}
fts_close(hier);

IMHO, this is much cleaner than the visitor pattern, but for a direct port of your Java code you can of course implement that on top of fts(3).

If your OS does not have fts(3), then check out the OpenBSD version of fts.c, which you should be able to paste into your program with at most minor modifications. You'll also need the header fts.h.

If mixing in c++ is acceptable there is something in boost for doing this, never used it though.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top