c++里如何遍历目录下的所有文件

来源:互联网 发布:sql convert函数 编辑:程序博客网 时间:2024/06/06 13:07

发现这个还不是很简单的问题。网上的一种方法是

system("cmd /c dir d://subsets//images2//*.bmp>>bmpfiles.txt");
 ifstream ifile;
 ifile.open("bmpfiles.txt",0);
 string filename;
 std::getline(ifile,filename);
 printf("%s",filename);

 

虽然可以遍历,不过获得的信息太多,不是一个文件名的列表。不过用system函数执行系统命令的方式倒是不错哦。

 

也有提到用boost库,或者mfc的。最后选择的方法是windows下的

 FindFirstFile和FindNextFile方法,网上的代码在unicode模式下工作有问题。改了下。代码如下。希望大家喜欢:)

 

 直接使用FindFirstFile,unicode模式下会被转化成FindFirstFileW, 带来很多的字符格式转化的噩梦。

int filesCount(const char* path,char* extname)
{
 WIN32_FIND_DATAA wfd;
 char* filter=new char[strlen(path)+5+1];
 sprintf(filter,"%s%s",path,extname);
 LPCSTR szPath=filter;
 int c=0;
 HANDLE hFind=::FindFirstFileA(szPath,&wfd);
 if(INVALID_HANDLE_VALUE == hFind)
      return -1;
 
 do{ c+=1;}while(FindNextFileA(hFind,&wfd));
 return c;

}

原创粉丝点击