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

c++读取某个文件夹下全部某种类型的文件

2014-12-21 00:22 295 查看
本文代码实现的功能为:

读取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:

1:http://www.verydemo.com/demo_c128_i5413.html

2:/article/2019286.html

3:http://blog.163.com/yuxiangdingdang@126/blog/static/10879785201032222340507/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: