C/C++ traverses all file or folder names under a folder (using Windows API)


foreword

In project development, it is often necessary to traverse some resource files in a certain folder. In order to avoid reinventing the wheel, I just recorded it here.

Implementation ideas

1. Give a folder name
2. Obtain the file handle
3. Filter out .the sum ..(upper level and current directory)
4. Identify folders, files, etc. by obtaining the attributes __finddata64_tof the structureattrib

//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// 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

source code

When your development environment is 32-bit, you need to change the __finddata64_t, _findfirst64, _findnext64three to _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));
    }

Guess you like

Origin blog.csdn.net/qq_45254369/article/details/131307877