2

I simply need to put all the files (or file names?) within a directory into a vector so that I can sort them and open them in order.

I literally have no idea how to do this since this my first encounter with C++. I have tried boost::filesystem but I am having no success as this is quite unfamiliar to me. Please help!

I've actually found a method I think will work however I am now struggling with adding a linker to the command line but I think if I ask about that here it'll exceed the scope of the original question.

1

2 Answers 2

7
namespace fs = boost::filesystem;
fs::directory_iterator b("path of directory"), e;
std::vector<fs::path> paths(b, e);

This includes sub-directories (but not their contents). If you want to exclude sub-directories, you can use fs::is_directory on a path to check if it is a directory. If you want to include the contents of the sub-directories, then you can use a recursive_directory_iterator instead of a directory_iterator.

2
  • With c++17 you no longer need boost and use std::filesystem
    – drake14w
    Jan 23, 2022 at 17:51
  • +1. For novices: 1) Using std::filesystem is the same, i.e. in this example just changing the boost::filesystem to std::filesystem would work. 2) default constructed directory_iterator equals "end iterator", thus the e in the 2nd line is end iterator. Jan 29 at 23:46
4

taken from your previous question:

std::vector<std::string> filenames;
dpdf = opendir("/data/files");
if (dpdf != NULL) {
   while (epdf = readdir(dpdf)) {
      filenames.push_back(std::string(epdf->d_name));
   }
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.