C/C++遍历文件夹下所有文件或文件夹名称(使用Windows API)


前言

在项目开发中,经常需要去遍历某一个文件夹下的一些资源文件。为了避免重复造轮子,刚好在此记录一下。

实现思路

1、给出一个文件夹名称
2、获取文件句柄
3、过滤掉...(上一级和当前目录)
4、通过获取__finddata64_t 结构体的attrib 属性即可识别文件夹、文件等

//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// Macros
//
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// File attribute constants for the _findfirst() family of functions
#define _A_NORMAL 0x00 // Normal file - No read/write restrictions
#define _A_RDONLY 0x01 // Read only file
#define _A_HIDDEN 0x02 // Hidden file
#define _A_SYSTEM 0x04 // System file
#define _A_SUBDIR 0x10 // Subdirectory
#define _A_ARCH   0x20 // Archive file

源代码

当你的开环境为32位时需要将__finddata64_t_findfirst64_findnext64三个改为_finddata32_t_findfirst_findnext

    std::string path = "./tset/"+ '*';
    __finddata64_t fileInfo;
    intptr_t hFile = _findfirst64(path.c_str(), &fileInfo);
    if(-1 != hFile)
    {
    
    
        do
        {
    
    
            if(_A_SUBDIR == fileInfo.attrib && 0 != strcmp(fileInfo.name, ".") && 0 != strcmp(fileInfo.name, ".."))
            {
    
    
                qDebug() << QString::fromStdString(fileInfo.name);
            }
        }while(0 == _findnext64(hFile, &fileInfo));
    }

猜你喜欢

转载自blog.csdn.net/qq_45254369/article/details/131307877