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
views:
328answers:
2
+3
Q:
C++ - Load all filename + count the number of files in a current directory + filter file extension
A:
The answer is Boost.Filesystem, specifically the directory_iterator.
Space_C0wb0y
2010-03-05 17:11:45
+3
A:
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;
}
Rupert Jones
2010-03-05 19:40:25
awesome :) I solve my problem with dirent.h library, but this is a great reference to boost.FileSystem. tyvm :)
Harry Pham
2010-03-08 21:27:16