C++获取文件夹下所有文件名称的三种方式

1

利用dos命令把文件夹下所有文件名存入指定文件,再从文件读取,存入vector中

         string imglist_file = "test_result\\imglist.txt";//存储文件名称列表
	string temp_imgname;
	string dir_command("dir ");
	dir_command += m_strImageSet + "/b > " + imglist_file;//m_strImageSet是我之前建立的变量 里面存放的是文件夹路径
	ifstream file(imglist_file.c_str(),ios::in);
	system(dir_command.c_str());
	vector <string> imglist;

	//把图像名称都存入vector中
           while(file>>temp_imgname)
	{
	     imglist.pushback(temp_imgname);
	}
	file.close();
		

2

利用_findfirst、_findnext获取所有文件名

         string temp_imgname;
	long   hFile   =   0;//文件句柄
	_finddata_t fileinfo;//文件信息
          vector<string> imglist	
	if((hFile = _findfirst(m_strImageSet+"\\*",&fileinfo)) !=  -1)//m_strImageSet是我之前建立的变量 里面存放的是文件夹路径
	{
		do
		{
			if((fileinfo.attrib &  _A_SUBDIR))
			{
				continue;//如果是目录则跳过
			}
			else
			{
				imglist.push_back(temp_imgname);
			}
		}while(_findnext(hFile, &fileinfo)  == 0);
	
		_findclose(hFile);
	}


3 利用finder获取

         WIN32_FIND_DATA FindFileData;
	int finder = 1;
	CString m_strImageSet_t = m_strImageSet +"\\*.*";)//m_strImageSet是我之前建立的变量 里面存放的是文件夹路径
	CString m_strImageSet_t1 = m_strImageSet +"\\";
         string imgname_temp;
         vector <string> imglist;
 	HANDLE hFind = FindFirstFile(m_strImageSet_t, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError ());
		return ;
	}
	else
	{  
		while(finder)
		{

			if((_tcscmp(FindFileData.cFileName,_T("."))==0)||(_tcscmp(FindFileData.cFileName,_T(".."))==0))//过滤资源管理器中默认两个文件夹.和..
			{
				finder = FindNextFile(hFind,&FindFileData);  
				continue;
			}
			else
                           {
				temp_imgname = FindFileData.cFileName; 
				imglist.pushback(temp_imgname);
				 
			}
			
			
		}
	}
	FindClose(hFind); 


     

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值