遍历目录下文件/子目录(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”的异常

原创粉丝点击