c++ 遍历文件夹

#include <windows.h>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <io.h>
using namespace std;
// 头文件要求: vector,  string
// 命名空间:    std
#define MAX_PATH_LENGTH 64
// 遍历结果保存结构体
// Filelist 为文件列表
// Foldlist 为文件夹列表
struct FoldInfo 
{
	vector<string> Filelist;
	vector<string> FoldList;
};

//遍历文件夹,FolderPath为要遍历的文件夹路径。Filter为遍历文件夹的过滤器,例如*.txt等
bool FindFolder(const char* FolderPath, const char* Filter, FoldInfo &info);

bool FindFolder(const char* FolderPath, const char* Filter, FoldInfo &info)
{
	string TargetName;
	int nPathLen = MAX_PATH_LENGTH;
	char* pChPath = new char[nPathLen];
	sprintf_s(pChPath, nPathLen, "%s/%s", FolderPath, Filter);
	WIN32_FIND_DATAA fileFindData;
	HANDLE hFind = ::FindFirstFileA((pChPath), &fileFindData);          

	if (hFind == INVALID_HANDLE_VALUE)  
	{
		delete pChPath;
		return false;
	}

	do 
	{
		if (!strcmp(fileFindData.cFileName,".") || !strcmp(&fileFindData.cFileName[0] , ".."))
		{
			continue;   
		}

		sprintf_s(pChPath, nPathLen, "%s/%s", FolderPath, fileFindData.cFileName);    //文件的完整路径
		TargetName = fileFindData.cFileName;

		if (fileFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{						
			info.FoldList.push_back(TargetName)	;				
		}else{						
			info.Filelist.push_back(TargetName)	;
		}

	}while (::FindNextFileA(hFind, &fileFindData)); 

	FindClose(hFind);                
	delete pChPath;    
	return true;
}

void print(string data)
{
	cout << data << endl;
}

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		MessageBoxA(0, "Please provide a Path!", "Error", MB_OKCANCEL);
		return -1;
	}
	if (_access(argv[1], 0) == -1)
	{
		MessageBoxA(0, "Path Is Not Exist!", "Error", MB_OKCANCEL);
		return -1;
	}

	FoldInfo fi;

	FindFolder(argv[1], "*.*", fi);

	cout << "Fold List\n------------------------------\n";
	for_each(fi.FoldList.begin(), fi.FoldList.end(), print);
	cout <<"\n\n\n";

	cout << "File List\n------------------------------\n";
	for_each(fi.Filelist.begin(), fi.Filelist.end(), print);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值