参考:
1.c/c++ 获取目录下文件列表https://blog.csdn.net/qq_23845067/article/details/51915200
2.C++ 获取文件夹下的所有文件名https://www.cnblogs.com/fnlingnzb-learner/p/6424563.html
程序:
程序一:
#include <iostream>
#include <string>
#include <io.h>
using namespace std;
void dir(string path)
{
long hFile = 0;
struct _finddata_t fileInfo;
string pathName, exdName;
// \\* 代表要遍历所有的类型,如改成\\*.jpg表示遍历jpg类型文件
if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) {
return;
}
do
{
//判断文件的属性是文件夹还是文件
cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]":"[file]") << endl;
} while (_findnext(hFile, &fileInfo) == 0);
_findclose(hFile);
return;
}
int main()
{
//要遍历的目录
string path = "E:\\result";
dir(path);
system("pause");
return 0;
}
该程序实现文件夹中所有文件夹或文件名字的输出,并判断是文件还是文件夹,文件输出file,文件夹输出folder。
程序二:
#include <iostream>
#include <vector>
#include <string.h>
#include <io.h>
using namespace std;
void getFolder(string path, vector<string>& folder)
{
long hFile =0;
struct _finddata32_t fileInfo;
string p;
if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileInfo)) != -1)
{
do
{
//如果是目录,存入列表
if((fileInfo.attrib & _A_SUBDIR))
{
if(strcmp(fileInfo.name, ".")!=0 && strcmp(fileInfo.name,"..")!=0)
folder.push_back(fileInfo.name);
}
else
{
continue;
}
}while(_findnext(hFile,&fileInfo)==0);
}
_findclose(hFile);
}
int main()
{
string path = "E:\\result";
vector<string> folder;
getFolder(path,folder);
cout<<folder.size()<<endl;
for(int i=0;i<folder.size();i++)
cout<<folder[i]<<endl;
return 0;
}
该程序,将文件夹下所有文件夹的名字存储,并在main函数中输出其个数,注意输出文件夹名称。
程序三:
#include <iostream>
#include <vector>
#include <string.h>
#include <io.h>
using namespace std;
void getFiles(string path, vector<string>& files,string file_type)
{
long hFile =0;
struct _finddata32_t fileInfo;
string p;
if((hFile = _findfirst(p.assign(path).append(file_type).c_str(),&fileInfo)) != -1)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if((fileInfo.attrib & _A_SUBDIR))
{
if(strcmp(fileInfo.name, ".")!=0 && strcmp(fileInfo.name,"..")!=0)
getFiles(p.assign(path).append("\\").append(fileInfo.name),files,file_type);
}
else
{
files.push_back(fileInfo.name);
}
}while(_findnext(hFile,&fileInfo)==0);
}
_findclose(hFile);
}
int main()
{
string path = "E:\\result";
vector<string> files;
string file_type="\\*.ply";
getFiles(path,files,file_type);
cout<<files.size()<<endl;
for(int i=0;i<files.size();i++)
cout<<files[i]<<endl;
return 0;
}
此程序是将文件夹中指定类型的文件输出并存储。
注:
只是用作记录,怕以后自己找不到这么多资料,就写出来了,如果对你有用,那也正好。
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询