Iterate over all files in a directory using BOOST_FOREACH

杀马特。学长 韩版系。学妹 提交于 2019-12-20 18:24:06

问题


Can you iterate over all files in a directory using boost::filesystem and BOOST_FOREACH? I tried

path dirPath = ...
int fileCount = 0;
BOOST_FOREACH(const path& filePath, dirPath)
    if(is_regular_file(filePath))
        ++fileCount;

This code compiles, runs, but does not produce the desired result.


回答1:


You can iterate over files in a directory using BOOST_FOREACH like this:

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp> 

namespace fs = boost::filesystem; 

fs::path targetDir("/tmp"); 

fs::directory_iterator it(targetDir), eod;

BOOST_FOREACH(fs::path const &p, std::make_pair(it, eod))   
{ 
    if(fs::is_regular_file(p))
    {
        // do something with p
    } 
}



回答2:


So I guessed I missed the boat on this one, but I was having a similar issue even after I found code that theoretically should work. The issue is the boost::filesystem::path data type takes the last char off of a string.

I was reading from a file and my path was "c:\one\two\three". But when i made it a path data type, the string was changed to "c:\one\two\thre". No idea what that is, but due to this the file location wasn't found and blah blah blah. What i did to fix it was just add another '\' to the end. That way it removes the '\' instead of the 'e'.

worked just fine after that. But as stated before, I have no idea why it did this. Hope this helps someone.




回答3:


Your dirPath is either not a sequence, either it's sequence is of size 1.

http://www.boost.org/doc/libs/1_48_0/doc/html/foreach.html

BOOST_FOREACH iterates over sequences. But what qualifies as a sequence, exactly? Since BOOST_FOREACH is built on top of Boost.Range, it automatically supports those types which Boost.Range recognizes as sequences. Specifically, BOOST_FOREACH works with types that satisfy the Single Pass Range Concept. For example, we can use BOOST_FOREACH with:

  • STL containers
  • arrays
  • Null-terminated strings (char and wchar_t)
  • std::pair of iterators

Note
The support for STL containers is very general; anything that looks like an STL container counts. If it has nested iterator and const_iterator types and begin() and end() member functions, BOOST_FOREACH will automatically know how to iterate over it. It is in this way that boost::iterator_range<> and boost::sub_range<> work with BOOST_FOREACH.



来源:https://stackoverflow.com/questions/8725331/iterate-over-all-files-in-a-directory-using-boost-foreach

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