遍历目录下文件/子目录(C/C++)
来源:互联网 发布:淘宝求好评短信 编辑:程序博客网 时间:2024/05/22 13:35
一、第三方库 Poco
Poco库的功能很强大,且支持跨系统,其中DirectoryIterator类具有强大的文件操作功能,下面就是个简单的遍历目录下文件的代码示例:
#include <stdio.h>#include <iostream>#include <string>#include "Poco/DirectoryIterator.h"using Poco::DirectoryIterator;#include "Poco/Timestamp.h"using Poco::Timestamp;using namespace std;// 自定义的结构体struct File_p{ Timestamp modified; string fileName; bool operator<(const File_p& f) const { return modified < f.modified; }};void GetAllFilesName(const char *cpath){ string pathString = cpath; try { DirectoryIterator it(pathString); // 实例化目录 DirectoryIterator end; int i = 1; while (it != end) // 类似迭代器功能 { if (it->isFile()) // 判断是文件还是子目录 { File_p file_tmp = { it->getLastModified(), it.name() }; // 获取时间戳及文件名称存放在自定义的结构体中 cout << "FileName: " << file_tmp.fileName << endl; } else { cout << "FileName: " << it.path().getFileName() << endl; } ++it; } } catch (...) { printf("[Error]\"%s\" not exist\n", pathString.c_str()); }}int main(){ string pathString = "C:\\Users\\Desktop\\Sconfig"; GetAllFilesName(pathString.c_str()); system("pause"); return 0;}
这里需要注意的是自定义结构体struct File_p,可根据需要自行定义里面的成员,如需要输出子目录时,可增加path成员。由于迭代器在遍历目录时是需要大小顺序的,故自定义的结构体需要重载运算符 ‘<’ ,这里是以文件的时间戳为大小比较顺序以便迭代器的正常遍历。
二、标准库
示例代码:
#include <string>#include <iostream>#include <io.h>using namespace std;int main(){ string pathName = "C:\\Users\\Desktop\\Sconfig\\*.log"; // 目录名称,支持通配符,这里是遍历所有以'.log'结尾的文件 intptr_t handle; // 存放_findfirst返回的目录句柄 struct _finddata_t stFileInfo; // 存放遍历到的文件或目录信息 handle = _findfirst(pathName.c_str(), &stFileInfo); if (handle == -1) return 1; cout << "fileName: " << stFileInfo.name << endl; while (_findnext(handle, &stFileInfo) == 0) { cout << "fileName: " << stFileInfo.name << endl; } _findclose(handle); // 关闭目录句柄 system("pause"); return 0;}
该代码不仅可以识别文件,也可识别子目录。
这里需要注意的是句柄handle的类型最好是intptr_t,因为不同系统对intptr_t的定义可能不一样,比如windows 10下就是typedef long long intptr_t,如果定义成long型,则_findfirst返回给long之后会发生截断,这样_findnext就出现类似”access violation”的异常
阅读全文
0 0
- 遍历目录下文件/子目录(C/C++)
- 用python遍历目录下文件(不包括子目录)
- 用python遍历目录下文件(包括子目录)
- C遍历文件夹下文件
- 获取某目录下的所有文件(包括子目录下文件)的数量(C#/VB.NET)
- 获取某目录下的所有文件(包括子目录下文件)的数量(C#/VB.NET)
- 获取某目录下的所有文件(包括子目录下文件)的数量(C#)
- 遍历目录下文件
- c语言实现windows下文件遍历
- c/c++ 获取目录下文件列表
- linux获取目录下文件 包含子目录
- linux C 遍历目录及其子目录
- linux C 遍历目录及其子目录
- linux C 遍历目录及其子目录
- linux C 遍历目录及其子目录
- linux C 遍历目录及其子目录
- linux C 遍历目录及其子目录
- [Windowns C]递归遍历指定目录下的子目录和文件
- 在eclipse中配置一个简单的spring入门项目
- JavaScript基础三
- plsql批量插入测试数据
- k均值聚类(K-means)
- Android studio 常用快捷键
- 遍历目录下文件/子目录(C/C++)
- springboot【14】事务管理
- 重入锁(ReentrantLock)、重入读写锁(ReentrantReadWriteLock)、线程通信(Condition)
- C语言引用&的个人理解
- 3DSlicer17:Logics
- Android 代码发送email含附件
- maven笔记(二)
- 北京首条磁悬浮列车线测试 年底可通车
- 深入浅出数据库索引原理