C++ - Load all filename + count the number of files in a current directory + filter file extension

会有一股神秘感。 提交于 2019-12-01 05:34:14

问题


I want to count the number of file in the current directory as well as load all file names in the array. If possible, I want to know how to filter file extension also


回答1:


Link the following program with -lboost_filesystem

#include <iostream>
#include <string>
#include <vector>

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/filesystem.hpp>

int main( int argc, char ** argv )
{
  std::string ext = ".jpg";

  std::vector<std::string> files;

  for ( boost::filesystem::directory_iterator it( boost::filesystem::initial_path() );
        it != boost::filesystem::directory_iterator(); ++it )
  {
    if ( boost::filesystem::is_regular_file( it->status() ) &&
         boost::algorithm::to_lower_copy( it->path().extension() ) == ext )
    {
      files.push_back( it->path().filename() );
    }
  }

  std::cout << "Number of files: " << files.size() << std::endl;
  std::copy( files.begin(), files.end(), std::ostream_iterator<std::string>( std::cout, "\n" ) );

  return 0;
}



回答2:


The answer is Boost.Filesystem, specifically the directory_iterator.



来源:https://stackoverflow.com/questions/2388402/c-load-all-filename-count-the-number-of-files-in-a-current-directory-fil

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