打开APP
userphoto
未登录

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

开通VIP
递归遍历某一路径下的所有文件(for windows or linux)
userphoto

2007.07.06

关注

递归遍历某一路径下的所有文件


    在windows下,可以使用FindFirstFile和FindNextFile来实现。

    而在Linux下,则可以使用opendir和readdir来实现。

    具体实现见下面两个函数,分别实现了打印某一路径下的所有
文件,包括子目录下的文件。在具体实现的时候需要注意设置路径。

注:
    下面两个程序都通过编译通过,且正常执行。
    windows下使用VC6.0编译;
    Linux下使用gcc 3.4.3编译。

#include <stddef.h>

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>       // stat 函数所在的文件

#include <dirent.h>

//for windows
void findAllFile(char * pFilePath)
{
 
 WIN32_FIND_DATA FindFileData;
 HANDLE hFind = INVALID_HANDLE_VALUE;
 char DirSpec[MAX_PATH + 1];  // directory specification
 DWORD dwError;
 
 strncpy (DirSpec, pFilePath, strlen(pFilePath) + 1);
 SetCurrentDirectory(pFilePath);
 strncat (DirSpec, "\\*", 3);
 
 hFind = FindFirstFile(DirSpec, &FindFileData);
 
 if (hFind == INVALID_HANDLE_VALUE)
 {
  printf ("Invalid file handle. Error is %u\n", GetLastError());
  return ;
 }
 else
 {
  if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY )
  {
   printf ("    %s\n", FindFileData.cFileName);
  }
  else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
   && strcmp(FindFileData.cFileName, ".") != 0
   && strcmp(FindFileData.cFileName, "..") != 0)
  {
   char Dir[MAX_PATH + 1];
   strcpy(Dir, pFilePath);
   strncat(Dir, "\\", 2);
   strcat(Dir, FindFileData.cFileName);
   
   findAllFile(Dir);
  }
  
  while (FindNextFile(hFind, &FindFileData) != 0)
  {
   if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
   {
    printf ("    %s\n", FindFileData.cFileName);
   }
   else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
    && strcmp(FindFileData.cFileName, ".") != 0
    && strcmp(FindFileData.cFileName, "..") != 0)
   {
    char Dir[MAX_PATH + 1];
    strcpy(Dir, pFilePath);
    strncat(Dir, "\\", 2);
    strcat(Dir, FindFileData.cFileName);
    findAllFile(Dir);
   }
   
  }
  
  dwError = GetLastError();
  FindClose(hFind);
  if (dwError != ERROR_NO_MORE_FILES)
  {
   printf ("FindNextFile error. Error is %u\n", dwError);
   return;
  }
 }
}


//for linux
void findAllFile(char * pFilePath)
{
 DIR * dir;
 dirent * ptr;
 struct stat stStatBuf;
 chdir(pFilePath);
        dir = opendir(pFilePath);
 while ((ptr = readdir(dir)) != NULL)
     {
  if (stat(ptr->d_name, &stStatBuf) == -1)
  {
   printf("Get the stat error on file:%s\n", ptr->d_name);
   continue;
  }
  if ((stStatBuf.st_mode & S_IFDIR) && strcmp(ptr->d_name, ".") != 0
    && strcmp(ptr->d_name, "..") != 0)
  {
   char Path[MAX_PATH];
   strcpy(Path, pFilePath);
   strncat(Path, "/", 1);
   strcat(Path, ptr->d_name);
   findAllFile(Path);
  }
  if (stStatBuf.st_mode & S_IFREG)
  {
   printf("  %s\n", ptr->d_name);
  }
  //this must change the directory , for maybe changed in the recured

function 
  chdir(pFilePath);
 }
     closedir(dir);
}

----------------------------------------------------------------------------------------------------

#include <stdio.h>
#include <errno.h>
 /*for directroy funcgion */
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <fstream>

//#define _LINUX


#ifdef _LINUX
#include <sys/types.h>
#include <dirent.h>
#endif

#ifdef _WIN32
#include <windows.h>
#endif

using namespace std;

vector<string> ReadDir(string dirName);
void PrintVec(vector<string> vecStr);
int ProcessFile(string fileName);


int main(int argc ,char **argv)
{
 int i;
 string dirName;
 vector<string> strVec;
 

 if (argc == 1)
 {
  strVec = ReadDir(".");
 }else{
  strVec = ReadDir(argv[1]);
 }
 cout << "the size of strVec is " << strVec.size()<<endl;
 for(vector<string>::iterator pos =strVec.begin();pos<strVec.end();pos++)
  ProcessFile(*pos);
 return 0;
}

void PrintVec(vector<string> vecStr){
 for(int i=0;i<vecStr.size();i++)
  cout << vecStr[i]<<endl;
}
#ifdef _LINUX
vector<string> ReadDir(string dirName)
{
 DIR* dp;
 struct dirent* ent;
 vector<string> ret;
 
 
 if((dp=opendir(dirName.c_str())) == NULL){
 
  exit(1);
 }
 
 errno = 0;
 while((ent=readdir(dp))!= NULL){
  //cout << setw(8)<< ent->d_ino <<"    "<< ent->d_name << endl;
  ret.push_back(ent->d_name);
 
 }
 
 if(errno != 0){
 
  exit(1);
 }
 
 if(closedir(dp) !=0){
 
  exit(1);
 
 }
 return ret;
}
#endif

#ifdef _WIN32
vector<string> ReadDir(string dirName)
{
   char *fileName;
   char curDir[ 256 ];
   char fullName[ 256 ];
   HANDLE fileHandle;
   WIN32_FIND_DATA findData;
   vector<string> ret;
     
   // print out the current directory name
   if( !GetFullPathName("*.*", 256, fullName,&fileName ) )
      return ret;
   cout << endl << "Directory - " << fullName << endl;
     
   // Loop through all files in the directory
   fileHandle = FindFirstFile("*.*",&findData );
   while ( fileHandle != INVALID_HANDLE_VALUE )
   {
      // If the name is a directory,
      // recursively walk it. Otherwise
      // print the file‘s data
      if( findData.dwFileAttributes &
         FILE_ATTRIBUTE_DIRECTORY )
      {
         //ListDirectoryContents( findData.cFileName,fileMask );
      }
      else{
         ret.push_back(findData.cFileName);
      }       
     // loop thru remaining entries in the dir
      if (!FindNextFile( fileHandle, &findData ))
         break;
   }
  
   // clean up and restore directory
   FindClose( fileHandle );
   return ret;
}
#endif
 
int ProcessFile(string fileName)
{
 // open input file
 int counter =0;
 ifstream file (fileName.c_str());
 // file opened?
 if (! file) {
  // NO, abort program
  cerr << "can‘t open input file \"" << fileName << "\""<< endl;
  return (0);
 }

 char c;
 while (file.get(c)) {
  if( c == ‘\n‘){
   counter++;
  }
 }
 cout << fileName << "---->" << counter <<endl;
 return counter;
 
 
}
 


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
VC C++ 遍历指定目录 Windows API
VC 遍历指定目录下的文件
Win32的时间类型
一段简单的C/C++病毒源程序
在Windows下,如何遍历某目录里所有文件?
获取目录下所有文件名
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服