C/C++编程遍历文件夹,统计当前文件个数,输出文件名

如题所述

这个要正对不同的操作系统,不同的操作系统,文件节点的存放方式不一样,读取的方式就不一样了。
可以利用for循环,像Linux
dir=opendir
(dirname)打开文件夹,返回目录指针,dp=readdir(dir)利用读目录,返回一行行读取目录的文件结构体指针,指针中存的有文件属性,是文件,还是文件夹。
通过判断是文件或者文件夹:
如果是文件,就就输出文件名dp->name
否则,就是一个文件夹
继续dir1=opendir(dp->name),dp1=readdir(dir1)..
一直循环到判断不到目录了。
windows应该也有类似的函数吧,这个我就么有用过了,你找找。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-06-10
#include<vector>
#include<iostream>
#include<windows.h>
using
namespace
std;
void
searchfileindirectroy(
const
string&
dir,
vector<string>&
outlist
)
{
win32_find_data
finddata;
handle
hhandle;
string
filepathname;
string
fullpathname;
filepathname
=
dir;
filepathname
+=
"\\*.*";
hhandle
=
findfirstfile(
filepathname.c_str(),
&finddata
);
if(
invalid_handle_value
==
hhandle
)
{
cout<<"error"<<endl;
return;
}
do
{
if(
strcmp(".",
finddata.cfilename)
==
0
||
strcmp("..",
finddata.cfilename)
==
0
)
{
continue;
}
fullpathname
=
dir;
fullpathname
+=
"\\";
fullpathname
+=
finddata.cfilename;
if(
finddata.dwfileattributes
&
file_attribute_directory
)
{
searchfileindirectroy(
fullpathname,
outlist
);
}
else
{
outlist.push_back(fullpathname);
}
}
while(
findnextfile(
hhandle,
&finddata
)
);
findclose(
hhandle
);
}
int
main()
{
vector<string>
pathlist;
searchfileindirectroy("d:\test",
pathlist);
return
0;
}
searchfileindirectroy
就是用来遍历指定文件夹下的文件及其子目录的。聪明的你一定知道它为什么可以遍历子目录!对啦,这个函数内部判断了取到的文件的属性是否是目录(
if(
finddata.dwfileattributes
&
file_attribute_directory
)
),如果是,就要递归调用本身函数,直到没有子目录为止。如果你不需要查询子目录,我想你应该知道怎么做。
我用的是远程登录,所以代码没办法copy过来,以上代码都是我手敲的,如果编译有错你就试着改改吧,函数本身的算法是可以工作的。
相似回答