统计文件目录下所有文件个数并打印文件名

/*  利用boost库中的filesystem可以轻松的实现计算某一目录下的文件个数及名字(包括子目录)
    本程序采用了命令行参数的形式
    结果存储在另一txt文件中
*/
#include  
#include  
#include 
#include  
#include 
#include 

namespace fs = boost::filesystem;  
namespace po = boost::program_options;
     
int get_filenames(const std::string& dir, std::vector& filenames)   //获取文件名和个数
{  
    fs::path path(dir);  
    if (!fs::exists(path))  //判断文件路径是否为空
    {  
        return -1;  
    }  
    
    fs::directory_iterator end_iter;  
    for (fs::directory_iterator iter(path); iter!=end_iter; ++iter)  
    {
        if (fs::is_regular_file(iter->status()))  
        {  
            filenames.push_back(iter->path().string()); 
        }  
      
        if (fs::is_directory(iter->status()))  
        {  
            get_filenames(iter->path().string(), filenames);//是目录则递归  
        }  
    }  
     
    return filenames.size();  //返回文件大小
}  

int main(int argc,char *argv[])
{
    po::options_description desc("Allowed options");  
    desc.add_options()  
        ("help,h", "produce help message")  
	    ("directory,d",po::value(), "output files' name and amount");  
  
    po::variables_map vm;  
    po::store(po::parse_command_line(argc, argv, desc), vm);  
    po::notify(vm);  

    if(vm.count("help"))  
    {  
        std::cout< filenames;
		int amount = get_filenames(vm["directory"].as(),filenames);
		std::ofstream out("filenames.txt");
		if (out.fail())
		{
			std::cout << "Error 2: failed to open the destination file." << std::endl;
			out.close();
			return 0;
		}		
        if (out.is_open())   
        {  
           out <<"amount:"<::iterator iter = filenames.begin(); iter != filenames.end(); iter++ )    
           {
		        out<<*iter<<" \n";
		   }
           out.close();  
        }  
	}
    else  
    {  
        std::cout<<"error1"<

你可能感兴趣的:(C/C++,Boost,C++,文件)