文章目录
通过C++获取文件夹中文件名以及文件路径,包括考虑子文件夹和不考虑子文件夹两种情况。
1 获取文件夹中所有文件名,包含子文件夹中的文件名
void getFiles(string path, vector <string> & files)
{
long hFile = 0;
struct _finddata_t fileinfo;
string pathp;
if ((hFile = _findfirst(pathp.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
getFiles(pathp.assign(path).append("/").append(fileinfo.name), files);
}
}
else
{
string filestr = fileinfo.name;
files.push_back(filestr);
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}

2 获取文件夹中所有文件路径,包含子文件夹中的文件路径
void getFiles(string path, vector <string> & files)
{
long hFile = 0;
struct _finddata_t fileinfo;
string pathp;
if ((hFile = _findfirst(pathp.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
getFiles(pathp.assign(path).append("//").append(fileinfo.name), files);
}
}
else
{
string filestr = fileinfo.name;
files.push_back(pathp.assign(path).append("//").append(filestr));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}

3 获取母文件夹中所有文件名,不包含子文件夹中的文件名
void getFiles(string path, vector <string> & files)
{
long hFile = 0;
struct _finddata_t fileinfo;
string pathp;
if ((hFile = _findfirst(pathp.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
continue;
}
}
else
{
string filestr = fileinfo.name;
files.push_back(filestr);
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}

4 只获取母文件夹中的文件路径,不包含子文件夹中的文件
void getFiles(string path, vector <string> & files)
{
long hFile = 0;
struct _finddata_t fileinfo;
string pathp;
if ((hFile = _findfirst(pathp.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
continue;
}
}
else
{
string filestr = fileinfo.name;
files.push_back(pathp.assign(path).append("//").append(filestr));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}

5 主函数以及文件夹情况
int main()
{
string basedir = "data";
vector <string> files;
getFiles(basedir, files);
int filenum = files.size();
for (int i = 0; i < filenum; i++)
{
cout << files[i] << endl;
}
system("pause");
return 0;
}
data文件夹

result文件夹

本文介绍使用C++获取文件夹中所有文件名及路径的方法,包括递归搜索子文件夹和仅检索当前目录的选项。通过四个不同函数实现,满足多种文件管理需求。
525





