打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
文件遍历
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <stack>
#include <windows.h>
using namespace std;
/* 
* 遍历lpszPath下所有文件及文件夹,并按顺序显示其中的内容.
*/
/*
* 如果扫描到文件夹,则将其存入 Dirs 队列中,并显示名称,
* 如果扫描到文件,则显示其名称;
* 当前文件夹处理完毕后就处理其下一级文件夹,下一级文件夹从队
* 列中得到.
*/
void function( LPCTSTR lpszPath,ostream & out)
{
     //开始查找;
     stack<TCHAR*> Dirs;
     stack<int> DirDepth;
     TCHAR *tmp=new TCHAR[lstrlen(lpszPath)+1];
     lstrcpy(tmp,lpszPath);
     if(tmp[lstrlen(tmp)-1]=='\\'
        tmp[lstrlen(tmp)-1]='\0';
     TCHAR szFind[MAX_PATH*2];
     TCHAR szFile[MAX_PATH*2];
     TCHAR *curdir;
  
     int curdepth=1; //当前文件夹的深度
     Dirs.push(tmp);
     DirDepth.push(curdepth);
       
     for(;!Dirs.empty();)
     {
         curdir=Dirs.top();
         curdepth=DirDepth.top();
         Dirs.pop();
         DirDepth.pop();
         lstrcpy(szFind,curdir);
         lstrcat(szFind, "\\*.*"); // 找所有文件
         WIN32_FIND_DATA wfd;
         HANDLE hFind = FindFirstFile(szFind, &wfd);
         if (hFind != INVALID_HANDLE_VALUE) // 如果找到
         {
         if (curdepth >1) out<<" ";
         for(int i=1;i<curdepth-1;++i)    out<<'|'<<" ";
         out<<'+'<<curdir<<endl;
             do{
                 if (wfd.cFileName[0] == '.')
                 continue; // 过滤"." ".." 这两个目录
                 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                 {
                     wsprintf(szFile, "%s\\%s", curdir, wfd.cFileName);
                     //function(szFile); // 如果找到的是目录,则进入此目录进行递归
                     TCHAR* tmp=new TCHAR[lstrlen(szFile)+2];
                     lstrcpy(tmp,szFile);
                     Dirs.push(tmp);
                     DirDepth.push(curdepth+1);
                 }
                 else
                 {
                     //输出文件名
                     out<<" ";
                     for(int i=1;i<curdepth;++i)
                     out<<'|'<<" ";
                     out<<wfd.cFileName<<endl;
                 }
             } while (FindNextFile(hFind, &wfd));
         }// if
         delete [] curdir;
         curdir = NULL;
         FindClose(hFind); // 关闭查找句柄
    }// for()
}
  
int main(int argc,char *argv[])
{
 ofstream fout("遍历结果.txt");
 if(argc<=1)
 {
     cerr<<endl<<"文件夹遍历,请输入路径:";
     TCHAR path[MAX_PATH];
     cin>>path;
     function(path,fout);
 }
 else
 {
    function(argv[1],fout);
 }
 return 0;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
用递归写Win32的文件夹遍历
Python模块整理(一):文件系统相关模块os
VC 遍历指定目录下的文件
ipkgmake制作ipk包
用API函数遍历指定驱动器、目录文件
如何用WindowsAPI函数遍历指定驱动器、目录的所有文件
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服