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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值