Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How can I get the list of files in a directory using C or C++?

How might I decide the list of files in a directory from inside my C or C++ code?

I'm not permitted to execute the ls command and parse the outcomes from inside my program.
by

2 Answers

sandhya6gczb
You can get the list of files in a directory Using the following code:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
std::string path = "/path/to/directory";
for (const auto & entry : fs::directory_iterator(path))
std::cout << entry.path() << std::endl;
}
RoliMishra
C++ now has a std::filesystem::directory_iterator, which can be used as

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
std::string path = "/path/to/directory";
for (const auto & entry : fs::directory_iterator(path))
std::cout << entry.path() << std::endl;
}

Also, std::filesystem::recursive_directory_iterator can iterate the subdirectories as well.

Login / Signup to Answer the Question.