C++遍历文件夹下的所有文件

时间:2022-11-11 07:27:06

数据分多个文件存储,读取数据就需要对多个文件进行操作。首先就需要定位到文件的名字,之后再对文件进行相应的读写操作。多次涉及多文件的读写操作,现将这个实现总结一下,方便自己和他人使用。具体代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "stdafx.h"
#include <stdio.h>
#include<iostream>
#include<vector>
#include <Windows.h>
#include <fstream> 
#include <iterator>
#include <string>
using namespace std;
#define MAX_PATH 1024 //最长路径长度
/*----------------------------
 * 功能 : 递归遍历文件夹,找到其中包含的所有文件
 *----------------------------
 * 函数 : find
 * 访问 : public 
 *
 * 参数 : lpPath [in]   需遍历的文件夹目录
 * 参数 : fileList [in]  以文件名称的形式存储遍历后的文件
 */
void find(char* lpPath,std::vector<const std::string> &fileList)
{
  char szFind[MAX_PATH];
  WIN32_FIND_DATA FindFileData;
  strcpy(szFind,lpPath);
  strcat(szFind,"\\*.*");
  HANDLE hFind=::FindFirstFile(szFind,&FindFileData);
  if(INVALID_HANDLE_VALUE == hFind)  return;
  while(true)
  {
    if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
      if(FindFileData.cFileName[0]!='.')
      {
        char szFile[MAX_PATH];
        strcpy(szFile,lpPath);
        strcat(szFile,"\\");
        strcat(szFile,(char* )(FindFileData.cFileName));
        find(szFile,fileList);
      }
    }
    else
    {
      //std::cout << FindFileData.cFileName << std::endl;
      fileList.push_back(FindFileData.cFileName);
    }
    if(!FindNextFile(hFind,&FindFileData))  break;
  }
  FindClose(hFind);
}
int main()
{
  std::vector<const std::string> fileList;//定义一个存放结果文件名称的链表
  //遍历一次结果的所有文件,获取文件名列表
  find("XXXX具体文件夹目录",fileList);//之后可对文件列表中的文件进行相应的操作
  //输出文件夹下所有文件的名称
  for(int i = 0; i < fileList.size(); i++)
  {
    cout << fileList[i] << endl;
  }
  cout << "文件数目:" << fileList.size() << endl;
  return 0;
}

总结

以上所述是小编给大家介绍的C++遍历文件夹下所有文件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/csdnwei/article/details/76619178