1. 程式人生 > 程式設計 >C++ 遍歷某個資料夾下所有檔案的方法步驟

C++ 遍歷某個資料夾下所有檔案的方法步驟

本文主要介紹了C++ 遍歷某個資料夾下所有檔案的方法步驟,分享給大家,主要給自己留個筆記。。

#include<iostream>
#include<string>
#include<io.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;

void fileSearch(string path)
{
  long hFile = 0;
  /*
    _finddata_t 儲存檔案各種資訊的結構體,<io.h>;
  */
  struct _finddata_t fileInfo;
  string pathName;
  /*
    \\* 表示符合的所有檔案;
    沒有找到即資料夾為空,退出;
    assign 表示把 pathName清空並置為path;
    append 表示在末尾加上字串;
    c_str 返回一個const char* 的臨時指標;
    _findfirst
      搜尋與指定的檔名稱匹配的第一個例項,若成功則返回第一個例項的控制代碼,否則返回-1L;
      函式原型:long _findfirst( char *filespec,struct _finddata_t *fileinfo );
  */
  if ( ( hFile = _findfirst(pathName.assign(path).append("\\*").c_str(),&fileInfo) ) == -1)
    return ;

  do {
    cout << path+"\\"+fileInfo.name << endl;
    /*
      資料夾下有 . 和 .. 目錄,不能進入搜尋;
      _A_SUBDIR 表示資料夾屬性;
    */
    if( strcmp(fileInfo.name,"..") && strcmp(fileInfo.name,".") && fileInfo.attrib==_A_SUBDIR )
      fileSearch(path+"\\"+fileInfo.name);
  } while ( _findnext(hFile,&fileInfo) == 0 );
  /*
    _findnext 搜尋與_findfirst函式提供的檔名稱匹配的下一個例項,若成功則返回0,否則返回-1 ;
    _findclose 結束查詢;
  */
  _findclose(hFile);
  return ;
}
int main()
{
  string path="E:\\Git";
  fileSearch(path);

  system("pause");
  return 0;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。