1. 程式人生 > >c++讀取某個資料夾下全部某種型別的檔案

c++讀取某個資料夾下全部某種型別的檔案

本文程式碼實現的功能為:

讀取images 資料夾下全部格式為.jpg格式的圖片名稱,並將名稱顯示出來。

以下為程式碼

getFileContents.h

#ifndef GETFILECONTENTS_H
#define GETFILECONTENTS_H

#include<string>
#include<vector>

using namespace std;

typedef vector<string> filelists;

filelists getImagePathes(const char* path,const char* extension);

#endif

getFileContents.cpp

#include "getFileContents.h"
#include<Windows.h>

using namespace std;
#define LEN 1024

wstring s2ws(const std::string& s)
{
	 int len;
	 int slength = (int)s.length() + 1;
	 len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
	 wchar_t* buf = new wchar_t[len];
	 MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
	 std::wstring r(buf);
	 delete[] buf;
	 return r.c_str();
}

// wchar_t to string
void Wchar_tToString(std::string& szDst, wchar_t *wchar)
{
wchar_t * wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);// WideCharToMultiByte的運用
char *psText; // psText為char*的臨時陣列,作為賦值給std::string的中間變數
psText = new char[dwNum];
WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);// WideCharToMultiByte的再次運用
szDst = psText;// std::string賦值
delete []psText;// psText的清除
}


filelists getImagePathes(const char* path,const char* extension)
{
	int n=0;
	WIN32_FIND_DATA findFileData;
	HANDLE handle;
	string searchPath,searchFile;
	filelists allFiles;
	
	searchPath=string(path)+"/*"+string(extension);

#ifdef UNICODE
	wstring stemp=s2ws(searchPath);
	LPCWSTR filePath=stemp.c_str();
#else
	LPCWSTR filePath=searchPath.c_str();
#endif

	handle=FindFirstFile(filePath ,&findFileData);
	if(handle==INVALID_HANDLE_VALUE)
	{
		fprintf(stderr,"ERROR(%s,%d): Cannot find (*.%s)files in directory %s\n",
			__FILE__, __LINE__, extension, path);
		exit(0);
	}
	do
	{
		if(findFileData.cFileName[0]=='.')
		{
			continue;
		}
		if(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			continue;
		}
		else
		{
			string temp;
			Wchar_tToString(temp,findFileData.cFileName);
			searchFile=string(path)+"/"+temp;
			allFiles.push_back(searchFile);
			n++;
		}
	}while(FindNextFile(handle,&findFileData));
	FindClose(handle);
	return allFiles;
}

main.cpp
#include<iostream>
#include<string>
#include<vector>

#include"getFileContents.h"

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

//typedef vector<string> filelists;


int main()
{
	
	filelists imageNames=getImagePathes("../../images",".jpg");
	for(int i=0;i<imageNames.size();i++)
	{
		cout<<imageNames[i]<<endl;
	}
	return 0;
}
執行結果如下圖:


Reference: