您的位置:首页 > 编程语言 > C语言/C++

c++遍历目录文件

2014-09-01 00:00 225 查看
摘要: 取网上demo修改而成

#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;
string sPathLast, sPath2 = sPath;
long hFile;

if ( sPath[sPath.length()-1] != '\\' )
sPath2 += "\\";

sPathLast = sPath2 + "*";
hFile = _findfirst(sPathLast.c_str(), &file);
if(hFile == -1)
return;
else
getFile(sPath2,fileList,file);

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

int main(int argc,char** argv)
{
string fileDir("E:");
vector<string> rfileList;

getFileList(fileDir,rfileList);
for(size_t i=0;i<rfileList.size();i++)
{
cout<<rfileList[i]<<endl;
}

system("pause");
return 0;
}


发现一个问题, 对中文目录不支持。。。待优化
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: