您的位置:首页 > 其它

如何在指定目录下获取指定文件尾缀的文件名

2015-07-24 16:51 411 查看
C++

使用两个文件file.h和file.cpp

file.h 包含class file的申明

file.cpp 包含class file的实现以及简单的测试主程序

///~file.h

#ifndef FILE_H_
#define FILE_H_

#include <iostream>
#include  <io.h>
#include  <direct.h>
#include  <cstring>
#include  <string>
#include  <vector>
#include  <iomanip>
#include  <ctime>
#include <malloc.h>
using namespace std;

class file{

private:
//path of file
string path;

public:
//constructor
file(const string name)
{
path = name;
}
//get all file or directory
void getFiles(vector<string> &file);
//get filename end with str
vector<string> getFilesWithStr(string str);

string getpath(){ return path;}
};

#endif // FILE_H_


///~file.cpp

#define FILE_TEST_
#include "file.h"

void file::getFiles(vector<string> &files)
{
//handle of file
long hFile = 0;
//information of file
struct _finddata_t fileinfo;

string p;
if((hFile=_findfirst(p.assign(path).append("/*").c_str(),&fileinfo)) != -1)
{
do{
// if it's a  directory, skip it
//else take it into vector
if(fileinfo.attrib)
{
if(fileinfo.attrib & _A_SUBDIR)
continue;
else
files.push_back(p.assign(path).append("/").append(fileinfo.name));

}
}while(_findnext(hFile,&fileinfo)==0);
}
}

vector<string> file::getFilesWithStr(string str)
{
vector<string> filelist;
vector<string> temp;
getFiles(filelist);
int n = str.size() + 1;
str = "."+str;
for(unsigned i = 0; i< filelist.size(); i++)
{
string str1 = filelist[i];
int pos = str1.size() - n ;
//compare str from pos for n letters
//you can also look up this method on the internet
if(str1.compare(pos,n,str) == 0)
{
//get str1 into vector
temp.push_back(str1);
}
}
return temp;
}

#ifdef FILE_TEST_
int main()
{
file path("j:");
vector<string> filelist;
path.getFiles(filelist);
//this a iterator of vector, it use for traversing vector
vector<string>::iterator iter=filelist.begin();
vector<string> temp;
temp= path.getFilesWithStr("txt");
iter=temp.begin();
for(;iter!=temp.end();iter++)
cout<<(*iter) + "\n";
}

#endif // FILE_TEST_


主函数之中我指定的是J盘下,后缀名为txt的文件。

以上为全部代码。

其中struct _finddata_t可以参考上面链接:

http://baike.baidu.com/link?url=EF5GReB-JD1P42qZQeEGr8vo42JqFncHWMozCXsafxkjMFubPu7RnqTOMPUPBxt2pBSYTxn7nXhAXt6H5W0nqq

_findfirst函数的用法可以参考一下链接:

http://blog.csdn.net/mxling/article/details/4761067
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: