C++bosst遍歷文件目錄,根據文件名返迴文件路徑。
- 2019 年 10 月 27 日
- 筆記
- VS2071安裝Boost庫
- 安裝boost庫
- 接著安裝boost_system-vc140(可根據開發需求,更改版本)
- 廢話不多說,上程式碼
// 測試程式.cpp : 此文件包含 "main" 函數。程式執行將在此處開始並結束。 // 函數功能:匹配某個目錄下的文件,返迴文件路徑 #include "pch.h" #include <string> #include <iostream> #include <boost/filesystem.hpp> using namespace std; string strHeadPath = ""; //匹配文件,返迴文件所在路徑 bool ReadFilePath(const string &strFilePath, string strCmpFile) { std::string::size_type nPos = strFilePath.rfind("\"); if (std::string::npos == nPos) { return false; } string strFileName = strFilePath.substr(nPos+1, strFilePath.size()); if (strFileName == strCmpFile) { strHeadPath = strFilePath;//strHeadPath定義成全局變數 return true; } return false; } //遍歷文件,尋找文件名對應路徑 //參數1:文件根路徑 參數2:要查找的文件名 void GetFileNameFromDir(string rootPath, string strCmpFile) { boost::filesystem::path dir(rootPath); if (boost::filesystem::exists(dir)) // 判斷路徑是否存在 { boost::filesystem::directory_iterator itEnd; boost::filesystem::directory_iterator itDir(dir); std::string strNewRoot(""); for (; itDir != itEnd; itDir++) // 遍歷路徑下所有文件 { strNewRoot = itDir->path().string(); if (boost::filesystem::is_directory(strNewRoot.c_str())) // 判斷文件是否是文件夾 { GetFileNameFromDir(strNewRoot, strCmpFile); } else { ReadFilePath(strNewRoot, strCmpFile); } } } } int main() { GetFileNameFromDir("D:\test", "haha.txt"); cout << strHeadPath.c_str() << endl; return 0; }
- 測試結果
- 總結:為了湊夠150字的隨筆發個小總結,其實沒毛總結的,此函數可以封裝成dll,實用的小函數,c++本作者也是邊學邊寫,平時比較忙後續偶爾會發一些數據安全相關的技術文章,湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字湊字。