c++ 遍歷文件夾

#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <io.h>
#include <windows.h>

using namespace std;

void getFileList(const string& sPath,vector<string>& fileList);

void getFile(const string& sPath,vector<string>& fileList,_finddata_t& file)
{
	if(file.attrib == _A_SUBDIR)
	{
		string filename = file.name;
		if(filename == "." || filename == "..")
		{
			return ;
		}
		string sAddPath = sPath;
		sAddPath += filename;
		sAddPath += "/";
		getFileList(sAddPath,fileList);
	}
	else
	{
		string sAddPath = sPath;
		sAddPath += file.name;
		fileList.push_back(sAddPath);
	}
}

void getFileList(const string& sPath,vector<string>& fileList)
{  

	struct _finddata_t file;
	long hFile;
	string sPathLast = sPath + "*"; // sPathLast = "c:\test\*.*"
	hFile = _findfirst(sPathLast.c_str(), &file);
	if(hFile == -1)
	{
		return;
	}
	else
	{
		getFile(sPath,fileList,file);
	}

	while(_findnext(hFile, &file) != -1)
	{
		getFile(sPath,fileList,file);
	}

}

int main(int argc,char** argv)
{
	if(argc > 2)
	{
		string saveFile(argv[1]);
		string fileDir(argv[2]);

		vector<string> rfileList;
		getFileList(fileDir,rfileList);

		for(size_t i=0;i<rfileList.size();i++)
		{
			cout<<rfileList[i]<<endl;
		}
	}
	return 0;
}
相關文章
相關標籤/搜索