C++文件与文件夹操作(2)--判断并筛选文件夹目录下特定后缀文件

本文目的:找到“D:/file/”文件夹下后缀名为“.csv”格式的第一个文件。

#include "stdafx.h"

#include <iostream>
#include <string>
#include "boost/filesystem.hpp"


using namespace std;
namespace bfs = boost::filesystem;


int getFileNames(const string& searchFilePath,vector<string>& fileName,const string& format);   // 函数声明


int main(int argc, char* argv[])    //主函数
{

        
string patternHomoPath = “D:/files/”;                              //文件夹路径
const string homoFileFormat = ".csv";                           // 指定文件后缀名
vector<string> homoFileNamesAll;                                // 初始化找到的文件列表 
int homoFileNumber = getFileNames(patternHomoPath,homoFileNamesAll,homoFileFormat);     //调用函数,返回文件列表个数
if (homoFileNumber == 0)
{
cout << "错误:未发现指定文件!!!" <<endl;
}
else
{
string homoFileName = homoFileNamesAll[0];       //取第一个符合条件的文件
}

return 0;
}


int getFileNames(const string& searchFilePath, vector<string>& searchFileName,const string &searchFileFormat)
{
bfs::path path(searchFilePath);
if (!bfs::exists(path))                                                         
{
return searchFileName.size();
}
bfs::directory_iterator end_iter;
for (bfs::directory_iterator iter(path); iter != end_iter; ++iter)
{
if (bfs::is_regular_file(iter->status()) &&bfs::extension(iter->path().string())==searchFileFormat)
{
searchFileName.push_back(iter->path().string());
}       
}
return searchFileName.size();
}

其中:bfs::exists:判断文件夹D:/file/是否存在;

          bfs::is_regular_file():判断是否为文件;

          bfs::extension():取文件的后缀名


参考文献:https://www.ibm.com/developerworks/cn/aix/library/au-boostfs/

                http://blog.csdn.net/tujiaw/article/details/7884329

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值