C++遍历文件夹

本文介绍了一个实用的文件操作工具类,提供了获取指定路径下所有文件夹、文件的方法,并支持检查文件或目录是否准备好,以及判断文件类型等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

01//written by baoer1024 on 2012-3-22
02#ifndef _FILE_H_
03#define _FILE_H_
04 
05#include <vector>
06#include <string>
07#include <time.h>
08#include <sys/stat.h>
09using namespace std;
10 
11const int MAX_DUR = 5*60;  //时间阈值
12 
13class File
14{
15public:
16    //获取路径下的所有文件夹
17    vector<string> GetFolders(const string &path);
18     
19    //获取路径下的所有文件,可指定文件后缀名
20    vector<string> GetFiles(const string &path, const string &postfix="");
21     
22    //检查文件或目录是否准备好,一定程度上防止数据正在拷贝的时候去读写。
23    //方法是检查文件或目录的access time是否在5分钟以前
24    bool IsPrepared(const string &path);
25     
26    //判断是否为文件夹
27    bool IsFolder(const string &path);
28     
29    //判断是否为文件
30    bool IsFile(const string &path);
31};
32 
33#endif

2. [代码]File.cpp    跳至 [1] [2] [全屏预览]

01//written by baoer1024 on 2012-3-22
02#include "File.h"
03#include <string.h>
04#include <stdio.h>
05#include <stdlib.h>
06#include <dirent.h>
07 
08//获取路径下的所有文件夹
09vector<string> File::GetFolders(const string &path)
10{
11   vector<string> folders;
12   struct dirent* ent = NULL;
13   DIR* pDir;
14   pDir = opendir(path.c_str());
15   while(NULL != (ent = readdir(pDir)))
16   {
17      string fullpath = path + "/" + ent->d_name;
18      //if(4 == ent->d_type)  //在nfs或xfs下,有的目录d_type也是0
19      if(IsFolder(fullpath))
20      {
21         if(strcmp(ent->d_name, ".")!=0 && strcmp(ent->d_name, "..")!=0)
22         {
23            folders.push_back(ent->d_name);
24         }
25      }
26   }
27   closedir(pDir);
28   return folders;
29}
30 
31//获取路径下的所有文件,可指定文件后缀名
32vector<string> File::GetFiles(const string &path, const string &postfix)
33{
34   vector<string> files;
35   struct dirent* ent = NULL;
36   DIR* pDir;
37   pDir = opendir(path.c_str());
38   while(NULL != (ent = readdir(pDir)))
39   {
40      string fullpath = path + "/" + ent->d_name;
41      //if(8 == ent->d_type)  //在nfs或xfs下,有的文件d_type也是0
42      if(IsFile(fullpath))
43      {
44         if(postfix == "" || strstr(ent->d_name, postfix.c_str())!=NULL)
45         {
46            files.push_back(ent->d_name);
47         }
48      }
49   }
50   closedir(pDir);
51   return files;
52}
53 
54//检查文件或目录是否准备好,一定程度上防止数据正在拷贝的时候去读写。
55//方法是检查文件或目录的access time是否在5分钟以前
56bool File::IsPrepared(const string &path)
57{
58    struct stat st;
59    stat(path.c_str(), &st);
60    return time(0)-st.st_ctime >= MAX_DUR;
61}
62 
63//判断是否为文件夹,用stat的标志来判断
64bool File::IsFolder(const string &path)
65{
66   struct stat st;
67   int ret = stat(path.c_str(), &st);
68   return ret>=0 && S_ISDIR(st.st_mode);
69}
70 
71//判断是否为文件,用stat的标志来判断
72bool File::IsFile(const string &path)
73{
74   struct stat st;
75   int ret = stat(path.c_str(), &st);
76   return ret>=0 && S_ISREG(st.st_mode);
77}
### C++ 遍历文件夹的示例代码 以下是几种常见的方法来实现 C++ 文件夹遍历功能: #### 方法一:使用 `FindFirstFile` 和 `FindNextFile`(Windows 平台) 这是 Windows 提供的标准 API,适合用来查找和遍历文件夹中的文件。 ```cpp #include <windows.h> #include <tchar.h> #include <iostream> void traverseDirectory(const TCHAR* path) { WIN32_FIND_DATA findData; HANDLE hFind; _tcscpy_s(findData.cFileName, MAX_PATH, path); _tcscat_s(findData.cFileName, TEXT("\\*")); hFind = FindFirstFile(findData.cFileName, &findData); if (hFind == INVALID_HANDLE_VALUE) { std::cerr << "Error opening directory." << std::endl; return; } do { if (_tcscmp(findData.cFileName, TEXT(".")) && _tcscmp(findData.cFileName, TEXT(".."))) { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // 如果是子目录,则递归遍历 TCHAR subPath[MAX_PATH]; _sntprintf_s(subPath, MAX_PATH, TEXT("%s\\%s"), path, findData.cFileName); traverseDirectory(subPath); } else { // 输出文件路径 std::wcout << path << "\\" << findData.cFileName << std::endl; } } } while (FindNextFile(hFind, &findData)); FindClose(hFind); } int main() { const TCHAR* targetDir = TEXT("C:\\YourTargetDirectory"); traverseDirectory(targetDir); return 0; } ``` 这种方法利用了 Windows 的 `FindFirstFile` 和 `FindNextFile` 函数[^3],能够高效地遍历目标文件夹及其子文件夹中的所有文件。 --- #### 方法二:使用 POSIX 接口(跨平台) 如果需要支持 Linux 或其他类 Unix 系统,可以采用标准库 `<dirent.h>` 进行文件夹遍历。 ```cpp #include <dirent.h> #include <stdio.h> #include <string.h> void processFiles(const char* folderPath) { DIR* dir = opendir(folderPath); if (!dir) { fprintf(stderr, "Cannot open directory: %s\n", folderPath); return; } struct dirent* entry; while ((entry = readdir(dir))) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; char fullPath[1024]; snprintf(fullPath, sizeof(fullPath), "%s/%s", folderPath, entry->d_name); if (entry->d_type == DT_DIR) { // 如果是子目录,则递归遍历 processFiles(fullPath); } else { // 处理文件逻辑 printf("Found file: %s\n", fullPath); } } closedir(dir); } int main() { const char* dataFolder = "/path/to/your/folder"; processFiles(dataFolder); return 0; } ``` 此代码片段展示了如何通过 POSIX 接口访问文件系统,并递归遍历整个目录结构[^2]。 --- #### 方法三:使用 OpenCV 的 `glob()` 函数 OpenCV 库提供了一个简单的工具函数 `cv::glob()`,可以直接用于检索指定模式的文件列表。 ```cpp #include <opencv2/core.hpp> #include <iostream> void listFilesWithGlob(const std::string& pattern) { std::vector<std::string> files; cv::glob(pattern, files, false); for (const auto& file : files) { std::cout << file << std::endl; } } int main() { std::string searchPattern = "C:/YourTargetDirectory/*.jpg"; // 修改为你想要的路径和扩展名 listFilesWithGlob(searchPattern); return 0; } ``` 该方法特别适用于图像处理场景,因为它允许轻松过滤具有特定后缀的文件[^1]。 --- #### 方法四:借助第三方库 Boost.Filesystem Boost 是一个强大的 C++ 扩展库集合,其中 `filesystem` 模块提供了丰富的接口来进行文件操作。 ```cpp #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; void traverseDirectory(fs::path root) { if (!fs::exists(root) || !fs::is_directory(root)) return; for (auto& entry : fs::recursive_directory_iterator(root)) { if (fs::is_regular_file(entry.path())) { std::cout << entry.path().string() << std::endl; } } } int main() { fs::path targetDir("C:/YourTargetDirectory"); traverseDirectory(targetDir); return 0; } ``` 这种方式不仅简洁明了,而且兼容多种操作系统环境[^3]。 --- ### 总结 以上四种方式分别针对不同需求进行了优化设计。具体选择取决于项目运行的目标平台以及开发者的个人偏好。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值