从某一文件夹下查找所有的文件

来源:互联网 发布:淘宝宠物医生 编辑:程序博客网 时间:2024/05/02 02:18

 

 

/***********************************************文件名:FindfileFromDirectory.h创建/修改者:benben创建/修改时间:2013.01.25功能:查找某一文件夹下面的所有文件***********************************************/#ifndef DV_FINDFILEFROMDIRECTORY_H#define DV_FINDFILEFROMDIRECTORY_H#include <Windows.h>#include "stdio.h"#include <Shlobj.h>#include <vector>#include <string>#include <iostream>using std::vector;using std::string;#ifdef UNICODEtypedef std::wstring MyString ;#else typedef std::string MyString;#endifclass DvFindFileFromDirectory{public:static void FindFileInDirectory(TCHAR *Path, std::vector<MyString>& vecPath){vecPath.clear();  // 这里清空传入的引用, 其实这个函数的目的也就是为了清空外面传入的容器delallfile(Path, vecPath);}private:static void delallfile(TCHAR *Path, std::vector<MyString>& vecPath){//vecPath.clear();  // 注意:这里这一句是不能调用的,因为这个函数要递归调用..TCHAR file[MAX_PATH];_tcscpy_s(file, sizeof(file)/sizeof(TCHAR), Path);_tcscat_s(file,  sizeof(file)/sizeof(TCHAR), TEXT("\\*.*"));WIN32_FIND_DATA wfd; HANDLE Find = FindFirstFile(file,&wfd); if (Find == INVALID_HANDLE_VALUE)  return;{do{if (wfd.cFileName[0] == TEXT('.')) {continue;}if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { TCHAR szFindPath[MAX_PATH];_tcscpy_s(szFindPath, sizeof(szFindPath)/sizeof(TCHAR),  Path); _tcscat_s(szFindPath, sizeof(szFindPath)/sizeof(TCHAR), TEXT("\\")); _tcscat_s(szFindPath,  sizeof(szFindPath)/sizeof(TCHAR), wfd.cFileName);delallfile(szFindPath, vecPath);  }{TCHAR FilePath[MAX_PATH]; _tcscpy_s(FilePath, sizeof(FilePath)/sizeof(TCHAR), Path); _tcscat_s(FilePath, sizeof(FilePath)/sizeof(TCHAR), TEXT("\\")); _tcscat_s(FilePath, sizeof(FilePath)/sizeof(TCHAR), wfd.cFileName); //std::wcout << FilePath << std::endl;vecPath.push_back(MyString(FilePath)); }  }while (FindNextFile(Find, &wfd));FindClose(Find);} }}; #endif

 

 

//  用法示例

#include "stdafx.h"#include "FindFileFromDirectory.h"#include <vector>#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){UNREFERENCED_PARAMETER(argc);UNREFERENCED_PARAMETER(argv);std::vector<MyString> vecPath; // 保存查找的文件集合DvFindFileFromDirectory::FindFileInDirectory(TEXT("C:\\DvResource\\"), vecPath);{std::vector<MyString>::iterator pos = vecPath.begin();std::vector<MyString>::iterator itEnd = vecPath.end();for (NULL; pos != itEnd; ++pos){if (MyString::npos != pos->find(TEXT(".exe"))){// 打开第一个找到的.exe 文件ShellExecute(NULL, TEXT("open"), pos->c_str(), NULL, NULL, SW_SHOWNORMAL);break;}}} return 0;}



 

原创粉丝点击