遍历文件夹方法2

#include<windows.h>
#include<iostream>
#include<string>
using namespace std;

//只能处理目录:lpPath只能是路径
void find(char *lpPath)
{
    char szFind[MAX_PATH];
   char szFile[MAX_PATH];

    WIN32_FIND_DATA FindFileData;

    strcpy(szFind,lpPath);
    strcat(szFind,"\\*.*");

    HANDLE hFind=::FindFirstFile(szFind,&FindFileData);
    if(INVALID_HANDLE_VALUE == hFind)    return;
    while(TRUE)
    {
        if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            if(FindFileData.cFileName[0]!='.')
            {
                strcpy(szFile,lpPath);
                strcat(szFile,"\\");
                strcat(szFile,FindFileData.cFileName);
                find(szFile);
            }
        }
        else
        {     
               cout<<FindFileData.cFileName<<endl;
        }
        if(!FindNextFile(hFind,&FindFileData))
            break;
    }
    FindClose(hFind);
}
//可同时处理目录和文件:path可以是路径,也可以是文件名,或者文件通配符
void _find(string path)
{
     //取路径名最后一个"\\"之前的部分,包括"\\"
    string prefix=path.substr(0,path.find_last_of('\\')+1);

    WIN32_FIND_DATA FindFileData;
    HANDLE hFind=::FindFirstFile(path.c_str(),&FindFileData);
    if(INVALID_HANDLE_VALUE == hFind)
    {
       cout<<"文件通配符错误"<<endl;
      return;
   }
    while(TRUE)
    {
      //目录
        if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            //不是当前目录,也不是父目录
            if(FindFileData.cFileName[0]!='.')
            {
                //查找下一级目录
                _find(prefix+FindFileData.cFileName+'\\'+"*.*");
            }
        }
        //文件
        else
        {  
   cout<<prefix<<endl;
   Sleep(100);
           //  cout<<FindFileData.cFileName<<endl;
        }
        if(!FindNextFile(hFind,&FindFileData))
              break;
    }
    FindClose(hFind);
}

void main()
{
    // find("E:");//目录:E盘
     _find("E:\\TDDOWNLOAD\\会计\\*.*");//E盘下所有文件E:\TDDOWNLOAD\会计

    //string str=".\\";
    //  string path;
    //  cout<<"请输入文件通配符:"<<flush;
    //  cin>>path;
    //  str=str+path;
    //  find((char*)str.c_str());//可以处理".",".." 不可以处理"*","..\\*"
    //  _find(str);//可以处理"*","..\\*" 不可以处理".",".."


   Sleep(200000);
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值