Question

I need to enumerate all the file in a folder and then navigate to the subfolder and do the same (recursion? sure).

Ideally the algorithm should work in the same way on linux & macos

DISCLAIMER: I have asked a similar question on POSIX: I'm now aware of VFS but I'm puzzled to use VFS for enumerate dir. Any suggestion ? Should I open a dir as file ? The only way is to use a library cross platform like qt ?

UPDATE: so no VFS way to work on directory? "*V*irtual *F*ile *S*ystem provides a single API for accessing various different file systems" but no way to enumerate directory.

The "readdir" etc solution will do the trick on any type of *NIX ? And on windows nothing better than the huge MingW lib? or partial impletion working on only some win like: https://github.com/xbmc/xbmc/blob/master/tools/TexturePacker/Win32/dirent.c

The BOOST seem to be a really cool solution but it's complex and academic. thnks in any case

LAST UPDATE:
I have found some more doc and now everything is a lot more clear. This question is a duplicate! opendir() and readdir() are the solution to enumerate and browse directory on linux. As shown on my example is quite easy to map them on windows (but the incoerent windowz fs make everything strange) and ntfw() is even more useful.

VFS (the virtual file switch) is a kernel feature that resolves this problem by creating an abstraction layer for file-system operations. closed doc here: linux programming interface

thnks!

Was it helpful?

Solution 3

Unix/Linux/Windows all have versions of readdir(). You can use it to get what the file system knows about files.

OTHER TIPS

You want to look at nftw. Here's an example that just recursively prints the contents of a directory in C (Untested):

#define _XOPEN_SOURCE 500
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ftw.h>


int
print( const char *path, const struct stat *s, int flag, struct FTW *f )
{
    puts( path );
    return 0;
}


int
main( int argc, char **argv )
{
    while( *++argv ) {
        if( nftw( *argv, print, 1024, FTW_DEPTH )) {
            perror( *argv );
            return EXIT_FAILURE;
        }
    }
    return EXIT_SUCCESS;
}

Here is how I do it using Boost.Filesystem:

#include "boost/filesystem.hpp"
#include <iostream>

int main () {
  for ( boost::filesystem::recursive_directory_iterator end, dir("./");
    dir != end; ++dir ) {
    // std::cout << *dir << "\n";  // full path
    std::cout << dir->path().filename() << "\n"; // just last bit
  }
}

Or, more succinctly:

#include "boost/filesystem.hpp"
#include <iostream>
#include <iterator>
#include <algorithm>

int main () {

  std::copy(
    boost::filesystem::recursive_directory_iterator("./"),
    boost::filesystem::recursive_directory_iterator(),
    std::ostream_iterator<boost::filesystem::directory_entry>(std::cout, "\n"));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top