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.
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.
#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).
@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! :-)