查找目录和子目录下所有文件

   这是我大三下期写的一个课程设计,根据输入的目录,查找当前目录和其子目录下所有文件并输出。

#include <direct.h>
#include <iostream>
#include <string.h>
#include <io.h>
#include <fstream> 
//#include <afxwin.h>
#include <windows.h>
using namespace std;

int count = 0;
int i;

//extern int FILE_ATTRIBUTE_DIRECTORY

int find_Directory(char *x,ostream & out)
{
    count++;
    _chdir(x);
    long handle;
   
    struct _finddata_t filestruct;
    //表示查找到的路径结果
    //开始查找工作, 找到当前目录下的第一个实体(文件或子目录),
    //″*″表示查找任何的文件或子目录, filestruct为查找结h
    handle = _findfirst("*", &filestruct);

    //如果handle为-1, 表示当前目录为空, 则结束查找而返回
    if((handle == -1))
        return 0;
    //检查找到的第一个实体是否是一个目录(filestruct.name为其名称)
    else
    {
        //如果返回0,则表示找到一个文件或目录
        while(!_findnext(handle,&filestruct))
        {   
            //如果找到当前实体名为"System Volume Information"则跳过
            if(!strcmp(filestruct.name,"System Volume Information"))
                continue;
            //如果找到的实体是一个目录,
            if(GetFileAttributes((LPCTSTR)filestruct.name) & FILE_ATTRIBUTE_DIRECTORY)
            {
                //目录".(当前目录)","..上一级目录),则递归调用查找文件方法
                if(filestruct.name[0] != '.')
                {
                    for(i=0;i<count;i++)
                    {
                        out<<"    ";
                        cout<<"    ";
                    }
                    out<<"|+"<<filestruct.name<<endl;//输出到记录文件""中
                    cout<<"|+"<<filestruct.name<<endl;
                   
                    find_Directory(filestruct.name,out);
                    _chdir("..");//将当前查找的位置转到当前目录的上一级
                    count--;
                }
            }
            else//如果找到的实体是文件则输出
            {       
                //格式化输出目录
                for(i=0;i<count;i++)
                {
                    out<<"    ";
                    cout<<"    ";
                }
                //输出文件名称及其大小
                out<<"|-"<<filestruct.name<<"       "<<filestruct.size<<"B"<<endl;
                cout<<"|-"<<filestruct.name<<"       "<<filestruct.size<<"B"<<endl;
            }
        }
    }
        return 1;
}


void main()
{
    char x[200];//定义一个字符数组,用于输入查询文件的目录
    cout<<"请输入要遍历的文件目录:";
    cin>>x;
    cout<<"文件目录是:"<<endl;
    ofstream   fout("遍历结果.txt");//找开一个文件用于记录文件目录
    find_Directory(x,fout);
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值