zoukankan      html  css  js  c++  java
  • C语言 遍历磁盘目录

    #include <iostream.h>
    #include <io.h>
    #include <string.h>
    #include "stdlib.h"
    
    const int MAXLEN = 1024; //定义最大目录长度
    unsigned long FILECOUNT = 0; //记录文件数量
    void ListDir(const char* pchData)
    {
        _finddata_t fdata; //定义文件查找结构对象
        long done;
        char tempdir[MAXLEN] = {0}; //定义一个临时字符数组
        strcat(tempdir, pchData); //连接字符串
        strcat(tempdir, "\\*.rar"); //连接字符串(搜索以RAR结尾的文件)
        //cout << tempdir << endl;
        done = _findfirst(tempdir, &fdata); //开始查找文件
        
        if(done!=-1) //是否查找成功
        {
            int ret = 0;
            while(ret!=-1) //定义一个循环
            {
                if(fdata.attrib != _A_SUBDIR) //判断文件属性
                {
                    //cout << fdata.name << endl;
                    if(strcmp(fdata.name, "...")!=0 &&
                        strcmp(fdata.name, "..") != 0 &&
                        strcmp(fdata.name, ".") != 0) //过滤
                    {
                        char dir[MAXLEN] = {0}; //定义字符数组
                        strcat(dir, pchData); //连接字符串
                        strcat(dir, "\\");
                        strcat(dir, fdata.name);
                        cout << dir << endl; //输出查找到的文件名
                        FILECOUNT++; //累加文件个数
                    }
    
                }
                ret = _findnext(done, &fdata); //查找下一个文件
                if(fdata.attrib == _A_SUBDIR && ret != -1) //判断文件属性,如果是目录,则递归调用
                {
                    
                    if(strcmp(fdata.name, "...") != 0 &&
                        strcmp(fdata.name, "..") != 0 && 
                        strcmp(fdata.name, ".") != 0) //过滤
                    {
                        char pdir[MAXLEN] = {0}; //定义字符数组
                        strcat(pdir, pchData); //连接字符串
                        strcat(pdir, "\\");
                        strcat(pdir, fdata.name);
                        cout << pdir << endl; //输出要递归调用的目录名
                        ListDir(pdir); //递归调用
                    }
                }
            }
        }
    
    
    
    
    }
     
    
    int main(int argc, char* argv[]) //主函数
    {
        while(true) //设计一个循环
        {
            FILECOUNT = 0;
            char szFileDir[128] = {0}; //定义一个字符数组,存储目录
            cin >> szFileDir; //让用户输入要查找的目录名
            if(strcmp(szFileDir, "e") == 0) //退出系统
            {
                break;
                //exit(0);
            }
            ListDir(szFileDir); //调用ListDir函数遍历目录
            cout << "共计" << FILECOUNT << "个文件" << endl; //统计文件数量
        }
     
        return 0;
    }
  • 相关阅读:
    SSH出现ls command not found
    SVN打包备份
    【转】Linux安装JDK1.7 prm
    任务
    java多线程
    JAVA开发中151个建议
    Linux Too Many OpenFiles
    【收藏】Linux tail命令
    Linux读取属性配置文件注意事项
    [转]Linux端口查看命令
  • 原文地址:https://www.cnblogs.com/pythonschool/p/2755276.html
Copyright © 2011-2022 走看看