snippetcppCritical
How can I get the list of files in a directory using C or C++?
Viewed 0 times
directoryhowfilestheusinglistcanget
Problem
How can I determine the list of files in a directory from inside my C or C++ code?
I'm not allowed to execute the
I'm not allowed to execute the
ls command and parse the results from within my program.Solution
UPDATE 2017:
In C++17 there is now an official way to list files of your file system:
Old Answer:
In small and simple tasks I do not use boost, I use
It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost (no offence, I like boost!).
In C++17 there is now an official way to list files of your file system:
std::filesystem. There is an excellent answer from Shreevardhan below with this source code:#include
#include
#include
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;
}Old Answer:
In small and simple tasks I do not use boost, I use
dirent.h. It is available as a standard header in UNIX, and also available for Windows via a compatibility layer created by Toni Rönkkö.DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost (no offence, I like boost!).
Code Snippets
#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;
}DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}Context
Stack Overflow Q#612097, score: 1136
Revisions (0)
No revisions yet.