how to get file names vs directory names in c++ (using boost filesystem library)

偶尔善良 提交于 2019-12-05 06:47:44

问题


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.


回答1:


is_directory()

boost::filesystem::is_directory(i->path());



回答2:


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


来源:https://stackoverflow.com/questions/31051317/how-to-get-file-names-vs-directory-names-in-c-using-boost-filesystem-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!