C++批量读取指定后缀文件
目录
- 核心功能说明
- 批量读取代码
博客长期更新,本文最新更新时间为:2025年6月14日。
核心功能说明
-
文件遍历机制
_findfirst()
:启动文件搜索,返回首个匹配文件句柄_findnext()
:获取下一个匹配文件_findclose()
:释放搜索资源
-
关键数据结构
struct _finddata_t {unsigned attrib; // 文件属性(普通/目录/隐藏等)time_t time_create; // 创建时间time_t time_access; // 访问时间time_t time_write; // 修改时间_fsize_t size; // 文件大小char name[_MAX_FNAME]; // 文件名 };
-
文件属性常量
_A_NORMAL // 普通文件 (0x00000) _A_RDONLY // 只读文件 (0x00001) _A_HIDDEN // 隐藏文件 (0x00002) _A_SYSTEM // 系统文件 (0x00004) _A_SUBDIR // 子目录 (0x00010) _A_ARCH // 存档文件 (0x00020)
批量读取代码
#include <iostream>
#include <string>
#include <vector>
#include <io.h> // Windows文件操作头文件
using namespace std;vector<string> getFilesByExtension(const string& folder, const string& ext) {vector<string> fileList;_finddata_t fileInfo;// 构造搜索模式:目录 + 通配符 + 后缀string searchPattern = folder + "\\*" + ext;// 开始搜索long handle = _findfirst(searchPattern.c_str(), &fileInfo);if (handle == -1L) {cerr << "未找到文件: " << searchPattern << endl;return fileList;}do {// 跳过"."和".."目录if (strcmp(fileInfo.name, ".") == 0 || strcmp(fileInfo.name, "..") == 0) continue;// 排除子目录(只保留文件)if (!(fileInfo.attrib & _A_SUBDIR)) {string fullPath = folder + "\\" + fileInfo.name;fileList.push_back(fullPath);}} while (_findnext(handle, &fileInfo) == 0); // 找到下一个文件_findclose(handle); // 关闭搜索句柄return fileList;
}int main() {string folder = "C:\\MyDocs";string extension = ".txt"; // 可改为.pdf/.jpg等vector<string> files = getFilesByExtension(folder, extension);cout << "找到 " << files.size() << " 个" << extension << "文件:\n";for (const string& path : files) {cout << "• " << path << endl;}return 0;
}