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

windows C++ 遍历目录,获取文件名和文件路径

2017-07-27 16:30 651 查看
void  GetFiles(string path, vector<string> &filesPath,  vector<string>& filesName)
{
WIN32_FIND_DATAA ffd;
memset(&ffd, 0, sizeof(ffd));
path.append("\\*");
HANDLE hFind = FindFirstFileA(path.c_str(), &ffd);
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (!strcmp(ffd.cFileName,".") || !strcmp(ffd.cFileName, ".."))
continue;
string newPath;
newPath = path.append("\\").append(ffd.cFileName);
GetFiles(newPath, filesPath, filesName);
}
else
{
char filePath[256] = { 0 };
sprintf_s(filePath, "%s/%s", path.c_str(), ffd.cFileName);
filesName.push_back(ffd.cFileName);
filesPath.push_back(filePath);
}
} while (FindNextFileA(hFind, &ffd) != 0);
FindClose(hFind);
}
#include <io.h>
void GetFiles(string path, vector<string>& files, vector<string>& fileNames)
{
//文件句柄
long   hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*.jpg").c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if ((fileinfo.attrib &  _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
string q;
GetFiles(q.assign(path).append("\\").append(fileinfo.name), files, fileNames);
}
else
continue;
}
else
{
string q;
files.push_back(q.append(path).append("\\").append(fileinfo.name));
fileNames.push_back(fileinfo.name);
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C