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

c++遍历某个路径下的所有文件

2017-10-17 17:01 267 查看
正确的代码如下,注意,路径需要用char*格式,否则会出现读不出来的错误。

findfirst函数文档如下:

_findfirst函数:long _findfirst(const char *, struct _finddata_t *);

第一个参数为文件名,可以用"*.*"来查找所有文件,也可以用"*.cpp"来查找.cpp文件。第二个参数是_finddata_t结构体指针。若查找成功,返回文件句柄,若失败,返回-1。

然后,_findnext函数:int _findnext(long, struct _finddata_t *);

第一个参数为文件句柄,第二个参数同样为_finddata_t结构体指针。若查找成功,返回0,失败返回-1。

最后:_findclose()函数:int _findclose(long);

int main()
{

struct info *str1;
struct info s;
long Handle;
struct _finddata_t FileInfo;
char* dir = "samplepicture\\*.*";
int count = 1;
if ((Handle = _findfirst(dir, &FileInfo)) == -1L)
printf("没有找到匹配的项目\n");
else
{
string File = FileInfo.name;
string FileName = c_PATH + File;
char* Filename = (char*)FileName.data();
cout << "第" << count << "个" << FileInfo.name << "文件" << endl;
//str1 = ReadXML(Filename);

//cout << s.name << "   " << s.xmin << "   " << s.xmax << "   " << s.ymin << "   " << s.ymax << endl;

while (_findnext(Handle, &FileInfo) == 0)
{
count++;
cout << FileInfo.name << endl;
string File = FileInfo.name;
string FileName = c_PATH + File;
char* Filename = (char*)FileName.data();
//cout << FileName << endl;
cout << "第" << count << "个.xml文件" << endl;
//	str1 = ReadXML(Filename);

//	cout << s.name << "   " << s.xmin << "   " << s.xmax << "   " << s.ymin << "   " << s.ymax << endl;

}

_findclose(Handle);
}
cout << count << endl;
//productXML();
system("pause");

return 0;

}


参考文献

[1].c++遍历某个路径下的所有文件.http://bbs.csdn.net/topics/390368005/
[2].用 _findfirst 和 _findnext 查找文件(windows可用) .http://blog.sina.com.cn/s/blog_56d8ea900100yejj.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: