0

Let's say I want to make a file manager, And I need to fetch the names of all the files in a given path. In python I would do something like: os.listdir(path). So is a c++ library like the OS module.

2 Answers2

2

You can use

#include <filesystem>

for this.

For some older compilers you might need to check if only experimental filesystem is available and use that.

#pragma once

#if __has_include(<filesystem>)

#include <filesystem>
namespace filesystem = std::filesystem;

#else

#include <experimental/filesystem>
namespace filesystem = std::experimental::filesystem;

#endif

Then to iterate over files:

   for (auto it : filesystem::directory_iterator("path/to/iterate"))
   {
       // Use it.path
   }

   // Or recursively
   for (auto it : filesystem::recursive_directory_iterator("path/to/iterate"))
   {
       // Use it.path
   }

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Lasersköld
  • 2,028
  • 14
  • 20
  • 1
    Note that neither `#pragma once` nor `__has_include` is standard C++. – Pete Becker Dec 17 '20 at 15:43
  • __has_include is standard since c++17 https://en.cppreference.com/w/cpp/preprocessor/include, and #pragma once is not standard, by implemented by most compilers – Lasersköld Feb 16 '21 at 09:17
  • 1
    Thanks for the correction on `__has_include`. And, yes, `#pragma once` is implemented by many compilers, but there are contexts where it cannot be relied on (for example networks with multiple paths to the same file), which is why it is not standard. – Pete Becker Feb 16 '21 at 13:50
0

You can import boost's filesystem libs like so:

#include <boost/filesystem.hpp>

Perhaps that works?

Jim O'Brien
  • 2,512
  • 18
  • 29
Trivo
  • 113
  • 8