2

When I use boost::filesystem to get a list of file names in a directory, I receive file names as well as directory names:

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
{
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        cout << i->path().filename().string() << endl;
    }
}

Output is like:

file1.txt
file2.dat
Folder1 //which is a folder

Is there a quick way to distinguish between files and folders? My OS is Windows 8.1, if it matters.

Bad
  • 4,967
  • 4
  • 34
  • 50
  • Possible duplicate of [How do I get a list of files in a directory in C++?](http://stackoverflow.com/questions/306533/how-do-i-get-a-list-of-files-in-a-directory-in-c) – malat Jan 05 '16 at 15:03

2 Answers2

6

Final code:

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
{
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        if (!is_directory(i->path())) //we eliminate directories in a list
        {
            cout << i->path().filename().string() << endl;
        }
        else
            continue;
    }
}

Output is like:

file1.txt
file2.dat
Bad
  • 4,967
  • 4
  • 34
  • 50
5

is_directory()

boost::filesystem::is_directory(i->path());
Simon
  • 1,616
  • 2
  • 17
  • 39