文件和文件夹目录的遍历 2007-08-16 16:26

这是我写的遍历目录的小程序,特地那出来和大家共享。

// 需要的几个头文件

#include <windows.h>

#include <stdio.h>

#include <stdlib.h>

#include <iostream>

/**

* 功能简介:实现深度遍历目录和文件

* 参数:char *,表示传入的是一个要遍历的起始路径

* 返回类型:void

**/

void FindFileAndDirectory(char * path)
{
 char FilePath[MAX_PATH] = {0};
 WIN32_FIND_DATA FindData;
 HANDLE FindHandle;
 ZeroMemory(&FindData,sizeof(WIN32_FIND_DATA));
 strcpy(FilePath,path);
 if (FilePath[strlen(FilePath) - 1] != '\\')
 {
  strcat(FilePath,"\\");
 }
 strcat(FilePath,"*");
 FindHandle = FindFirstFile(FilePath,&FindData);
 if (FindHandle == INVALID_HANDLE_VALUE)
 {
  cout<<"查找失败,程序退出!"<<endl;
  return;
 }
 do
 {
  if ((FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
   && strcmp(FindData.cFileName,".")
   && strcmp(FindData.cFileName,".."))
  {
   char TempPath[MAX_PATH] = {0};
   strcpy(TempPath,path);
   if (TempPath[strlen(TempPath) - 1] != '\\')
   {
    strcat(TempPath,"\\");
   }
   strcat(TempPath,FindData.cFileName);
   cout<<"The Path Is: "<<TempPath<<endl;
   FindFileAndDirectory(TempPath);
  }
  else if (strcmp(FindData.cFileName,".") && strcmp(FindData.cFileName,".."))
  {
   char TempPath[MAX_PATH] = {0};
   strcpy(TempPath,path);
   TempPath[strlen(TempPath) - 1] = 0;
   strcat(TempPath,FindData.cFileName);
   cout<<"The File Is: "<<TempPath<<endl;
  }
 } while(FindNextFile(FindHandle,&FindData));
 FindClose(FindHandle);
}

当传入文件路径时它回遍历出所有的文件夹和文件。有兴趣大家可以共同讨论。

这是新加的c++版的

#include<iostream>
#include<io.h>
using namespace std;

#define BUF_SIZE 256

void findfileanddirectory(char * path)
{
 _finddata_t filedata;
 long lf;
 char lpath[256] = {0};
 strcpy(lpath,path);
 if (lpath[strlen(lpath) - 1] != '\\')
 {
  strcat(lpath,"\\");
 }
 strcat(lpath,"*.*");
 lf = _findfirst(lpath,&filedata);
 if (lf == -1)
 {
  cout<<"查找文件失败,返回!"<<endl;
  return;
 }
 do
 {
  if ((filedata.attrib & _A_SUBDIR)&&strcmp(filedata.name,".") && strcmp(filedata.name,".."))
  {  
   char bufpath[BUF_SIZE] = {0};
   strcpy(bufpath,path);
   if (bufpath[strlen(bufpath) - 1] != '\\')
   {
    strcat(bufpath,"\\");
   }
   strcat(bufpath,filedata.name);
   cout<<"The Path Is: "<<bufpath<<endl;
   findfileanddirectory(bufpath);
  }
  else if (strcmp(filedata.name,".") && strcmp(filedata.name,".."))
  {
   char bufpath[BUF_SIZE] = {0};
   strcpy(bufpath,path);
   if (bufpath[strlen(bufpath) - 1] != '\\')
   {
    strcat(bufpath,"\\");
   }
   strcat(bufpath,filedata.name);
   cout<<"The Path Is: "<<bufpath<<endl;
  }
 } while(_findnext(lf,&filedata) == 0);
 _findclose(lf);
}

猜你喜欢

转载自www.cnblogs.com/lu-ping-yin/p/10988607.html