龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

VC文件目录常见操作实例汇总(2)

时间:2014-10-23 11:03来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: #include Windows.h #include tchar.h #include list #include set #include cassert #include string typedef std::basic_stringTCHAR _tstring; //宽字符串 typedef std::list_tst

复制代码 代码如下:
  #include <Windows.h>
  #include <tchar.h>
  #include <list>
  #include <set>
  #include <cassert>
  #include <string>
  typedef std::basic_string<TCHAR> _tstring;  //宽字符串
  typedef std::list<_tstring> _tslist; //字符串链表
 /*

  返回文件名的链表。

  filepath  目录的完整路径,不带//

  filefilterlist 文件扩展名列表,可以是多种类型的组合,比如说.txt;.xls;.doc

  isordered  是否对文件名排序 

 */

_tslist  SearchFile(LPCTSTR filepath, LPCTSTR filefilterlist = _T(".*" ), bool isordered = true)

{

    assert(filepath != NULL);  

    TCHAR buffer[MAX_PATH];

#if _MSC_VER > 1310 

/* 1310 for Microsoft Visual C++ .NET 2003. 1310 represents /version 13 and a 1.0 point          release. The Visual C++ 2005 compiler version is 1400, the number.

*/

    _tcscpy_s(buffer, filepath); //_tcscpy_s is a micro for strcpy_s and strwcpy_s 

#else

    _tcscpy(buffer,filepath);  //

#endif

    _tslist filenamelist; // initial length is 100

    WIN32_FIND_DATA finddata;

    HANDLE searchhandle = INVALID_HANDLE_VALUE;

    size_t length= _tcslen(filepath);

    if (buffer[length-1] != _T('//'))
   {

        _tcscat_s(buffer,_T("//*")); // 向字符串结尾添加/*, 用来查找所有文件
    }
    if ( (searchhandle = ::FindFirstFile(buffer, &finddata)) != INVALID_HANDLE_VALUE )
    {

      while (::FindNextFile(searchhandle, &finddata) != 0)
     {

        if ( !(finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )   // 为文件            
       {
          if (  !_tcsicmp(filefilterlist, _T(".*")))   // 将所有文件输出到链表

             filenamelist.push_back(finddata.cFileName);
          else
         {
            //get file filter list string, a example, file filter may be ".txt;.xls;.doc"
            _tstring filterstring = filefilterlist;
            _tstring filename(finddata.cFileName);
            _tstring::size_type index = filename.find_last_of(_T('.'));
            if (index == _tstring::npos) // 文件没有扩展名,跳过
               continue;
            else
           {
                 _tstring extname = filename.substr(index+1);  //取得文件的扩展名
                _tstring::size_type exist;
                exist = filterstring.find(extname);
                if (exist != _tstring::npos)  //判断文件的扩展名是否在扩展名列表里
                 filenamelist.push_back(finddata.cFileName);
              }
            }
         }
      }
    }
    ::FindClose( searchhandle );

收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!
按钮 内容不能为空!
立刻说两句吧! 查看0条评论
精彩图集

赞助商链接