Skip to content

Instantly share code, notes, and snippets.

@marcinwol
Created February 25, 2015 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcinwol/4ed7bb452dc004e0dce2 to your computer and use it in GitHub Desktop.
Save marcinwol/4ed7bb452dc004e0dce2 to your computer and use it in GitHub Desktop.
Example showing how to get all paths in a given folder using dirent readdir method.
#include <errno.h>
#include <dirent.h>
#include <iostream>
#include <vector>
using namespace std;
int dir_scan(const string & in_path, vector<string> & found_paths)
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir (in_path.c_str())) != nullptr)
{
while ((ent = readdir (dir)) != NULL)
{
cout << ent->d_name << endl;
found_paths.emplace_back<string>(ent->d_name);
}
closedir (dir);
}
else
{
perror("could not open directory ");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int main(int argc, char **argv) {
std::string in_folder = "/tmp";
std::vector<string> found_files;
if (dir_scan(in_folder, found_files) == 1)
{
cout << "some error occured";
return 1;
}
for (const string & a_file : found_files)
{
cout << a_file << endl;
}
cout << "\nFound "<< found_files.size() <<" files" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment