Create a file list (platform-independent way?)

Hi guys,

although this questions has been asked many times, I haven't found a working solution for me yet.
I want to create a function that returns a std::vector<std::string> with contents of a directory.

std::vector<std::string> DirList(std::string directory) {
std::vector<std::string> dirItems;

DIR *verzeichnis;
struct dirent *files;
verzeichnis=opendir(directory.c_str());

while(files = readdir(verzeichnis))
{
dirItems.push_back(files->d_name);
}
closedir(verzeichnis);
}

This code is not working for me, it seems it's randomly printing some characters onto the console window and after that, it crashes. (still Code::Blocks)
Boost library... it's ok, but it didn't really work for me for compiler issues.
I would be glad to get a solution, but wasn't able to work with the Win32 API although it's easier because I need it platform-independent.

Thanks,
Florian
You forgot to return dirItems, it would seem.
Use the filesystem library. An example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <codecvt>
#include <iostream>
#include <locale>

#if __cplusplus < 201703L
  #include <boost/filesystem.hpp>
  namespace fs = boost::filesystem;
#else
  #include <filesystem>
  namespace fs = std::filesystem;
#endif

int main( int argc, char** argv )
{
  fs::path root = (argc == 2) ? argv[ 1 ] : ".";
  
  auto first = fs::recursive_directory_iterator( root );
  auto last  = fs::recursive_directory_iterator();
  
  std::wstring_convert< std::codecvt_utf8_utf16<wchar_t> > utf8_cvt;
  auto utf8 = [&utf8_cvt]( const std::wstring& s )
  {
    return utf8_cvt.to_bytes( s );
  };
  
  while (first != last)
  {
    std::cout << utf8( first->path().native() ) << "\n";
    ++first;
  }
}

Unless you have a compiler that implements the C++17 filesystem, you'll currently have to use Boost. Make sure to link with boost_filesystem and boost_system (in that order if using GCC).

Good luck!
@Duthomhas
Thank you very much for your solution with the recursion. But as @helios told, he's right, I've forgotten the return value. Now it works! :-)
Topic archived. No new replies allowed.