统计文件目录下所有文件个数并打印文件名
2016-02-24 16:20
1006 查看
/* 利用boost库中的filesystem可以轻松的实现计算某一目录下的文件个数及名字(包括子目录) 本程序采用了命令行参数的形式 结果存储在另一txt文件中 */ #include <boost/filesystem.hpp> #include <iostream> #include <string> #include <fstream> #include <vector> #include <boost/program_options.hpp> namespace fs = boost::filesystem; namespace po = boost::program_options; int get_filenames(const std::string& dir, std::vector<std::string>& 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<std::string>(), "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<<desc<<std::endl; return 1; } if(vm.count("directory")) { std::vector<std::string> filenames; int amount = get_filenames(vm["directory"].as<std::string>(),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:"<<amount<<" \n"; for(std::vector<std::string>::iterator iter = filenames.begin(); iter != filenames.end(); iter++ ) { out<<*iter<<" \n"; } out.close(); } } else { std::cout<<"error1"<<std::endl; } return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- boost相关小知识(长期顶置更新)
- 命令行小技巧:读取文件的不同方式
- IE:临时文件保存法
- 文件的读出 编辑 管理
- 文件遍历排序函数
- 在线用表单建立文件夹
- VB获取文件大小的方法
- 文件、目录,文本文件等多种操作类
- 处理驱动器和文件夹
- 用vbs删除某些类型文件和磁盘空间报告的脚本
- Ruby实现批量对文件增加前缀代码分享
- C#获取文件夹及文件的大小与占用空间的方法
- delphi制作wav文件的方法
- PowerShell实现查询打开某个文件的默认应用程序
- bat 文件 学习使用指南
- IIS配置文件隐患