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.
Asked
Active
Viewed 1,848 times
0

hackerman69
- 19
- 3
-
4Yes. You have [`std::filesystem`](https://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c). – Potados Dec 17 '20 at 11:46
-
This should be an answer on its own. – Marcin Zdun Dec 17 '20 at 12:48
2 Answers
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
-
1Note 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
-
1Thanks 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

Jim O'Brien
- 2,512
- 18
- 29

Trivo
- 113
- 8
-
While Boost is a valuable resource, there are standard answers as well, in this case
– Marcin Zdun Dec 17 '20 at 12:47