Boost FileSystems, need help understanding what I'm doing
-
11-06-2021 - |
Frage
I wrote a program using boost filesystems almost a year ago, and I am now trying to go back and use that for a reference, but I'm not sure exactly what is going on with the code, and if there might be a better way to do it.
Here is what I had done to iterate through a directory.
vector <directory_entry> entry;
copy(directory_iterator("path"), directory_iterator(), back_inserter(entry));
This gets me a vector with directory entries for all of the files and directories inside the directory at "path"
Then I would sort them into two vectors of paths, one for files, one for directories, using is_regular_file.
I was working with openAL, and I would have to do this type of conversion to get things working.
path fp = file[0]; //file a vector of directory_entry
string fps = fp.string();
buffer[0] = AlutCreateBufferFromFile(fps.c_str());
And this worked, but I am thinking this all must not be very correct how I'm using it. Anyways, I just wanted to see if anyone could give me a little advice.
Lösung
Your code looks correct.
You can avoid a couple variable declarations like so:
buffer[0] = AlutCreateBufferFromFile(file[0].string().c_str());
You can also avoid copying the directory entries into a vector
and iterate over the directory entries directly:
directory_iterator cur("path");
directory_iterator end;
while (cur != end)
{
path p = *cur;
... // use p
++cur;
}
In C++11, you can improve on the loop further with lambdas:
for_each(directory_iterator("path"), directory_iterator(), [](const path& p)
{
// use p
});