您的位置:首页 > 编程语言 > C语言/C++

window环境下 C语言遍历一个目录下的文件

2017-02-24 15:41 295 查看

window环境下  C语言遍历一个目录下的文件

#include <iostream>

#include<stdlib.h>

#include <io.h> 

#include <string.h> 

 

using namespace std;

const int MAXLEN = 1024; //定义最大目录长度 

unsigned long SumFile = 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; //输出查找到的文件名 

          SumFile++; //累加文件个数 

         } 

       }    

          ret = _findnext(done, &fdata); //查找下一个文件 

 

     } 

   } 



int main(int argc, char* argv[]) //主函数 



 while(true) //设计一个循环 

 { 

 SumFile = 0; 

  char szFileDir[128] = {0}; //定义一个字符数组,存储目录 

   cin >> szFileDir; //让用户输入要查找的目录名 

  ListDir(szFileDir); //调用ListDir函数遍历目录 

 cout << "磁盘存在" << SumFile << "个此文件" << endl; //统计文件数量 

  } 

system("pause");

return 0; 

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: