本文目的:找到“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