C++遍历文件夹获取文件列表
本文实例类似遍历一个文件夹然后获得该文件夹下的文件列表,可以随意切换文件目录,本来是用在我们小组写的简易ftp服务器上的一个给客户端显示的一个小插件,总之单拿出来应该没啥含量,调用了windows的一些API。
实例代码:
#include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<fstream>
#include<stdio.h>
#include<vector>
#include<string>
#pragmacomment(lib,"winmm.lib")
usingnamespacestd;
voidMainMenu()
{
printf("请选择操作\n");
printf("1.显示当前文件夹的所有文件\n");
printf("2.返回上一级\n");
printf("3.进入文件夹\n");
printf("4.进入指定文件夹\n");
printf("5.退出\n");
}
voidShowFileList(stringfilename)
{
WIN32_FIND_DATAAp;
vector<string>filelist;
HANDLEh=FindFirstFileA(filename.c_str(),&p);
filelist.push_back(p.cFileName);
while(FindNextFileA(h,&p))
{
filelist.push_back(p.cFileName);
if(filelist.back()=="."||filelist.back()=="..")
{
filelist.pop_back();
}
}
for(inti=0;i<filelist.size();i++)
{
cout<<filelist[i]<<endl;
}
}
voidShowLastFileList(string&filepath)
{
stringfilepath2=filepath;
stringtmp="../";
tmp+=filepath2;
filepath=tmp;
ShowFileList(tmp);
}
voidShowSelectFileList(stringfilepath)
{
stringyourchoose;
cin>>yourchoose;
yourchoose+='/';
stringfilepath2=filepath;
yourchoose+=filepath2;
ShowFileList(yourchoose);
}
voidcase4(stringfilepath)
{
stringfilename;
cin>>filename;
filename+='/';
filename+=filepath;
ShowFileList(filename);
}
intmain()
{
stringfilepath;
filepath="*.*";
stringfilePath=filepath;
while(1)
{
system("CLS");
MainMenu();
intn;
cin>>n;
switch(n)
{
case1:
system("CLS");
ShowFileList(filePath);
system("pause");
break;
case2:
system("CLS");
ShowLastFileList(filePath);
system("pause");
break;
case3:
system("CLS");
ShowSelectFileList(filePath);
system("pause");
break;
case4:
system("CLS");
case4(filepath);
system("pause");
break;
case5:
exit(0);
break;
default:
break;
}
}
return0;
}
以上就是C++遍历文件夹的相关操作,希望对大家的学习有所帮助。