QT local file search, file/folder creation, file/directory decompression

Above code:

head File

#ifndef FDWINGS_H
#define FDWINGS_H
#include <fstream>
#include <string.h>
#include <windows.h>
#include <iomanip>
#include <io.h>
#include <iostream>
#include <sys/stat.h>
#include <sstream>
#include <QtWidgets>
#include <QStringListIterator>
#include <QRegularExpressionMatch>
#include <QTextCodec>
#include <QtGui/private/qzipreader_p.h>
#include <QtGui/private/qzipwriter_p.h>

using namespace std;

enum MatchingMode{
    Exact = 0,
    Simple};

class Nlwingsing
{

public:

    Nlwingsing(QStringList DTpath = QStringList(),
               QStringList KeyWord = QStringList(),
               QStringList Suffix = QStringList(),
               MatchingMode McMode = MatchingMode::Simple);

    QStringList GetMatchingResult();

    void setDTpath(QStringList DTpath);

    void setKeyWord(QStringList KeyWord);

    void setPostFix(QStringList Suffix);

    void setMatchMode(MatchingMode MatchMode);

    QString MakePath(QString Dir);

    QString MakeFile(QString File);

    void ZipGet(QString ZipPath, QString Directory = NULL, QStringList Filter = {});

    void ZipPush(QString ZipPath, QString Directory = NULL);

    QString CombinationPath(QString Path, bool IsretainSuffix=true);

    QStringList getFileListUnderDir(QString dirPath);

    const std::string BscTgb12(const char *bcc);

    const std::string Gb12TBsc(const string gbc);

    void __Init__();

private:
    QStringList MatchPath;
    QStringList MatchPostFix;
    QStringList MatchKeyWord;
    MatchingMode MatchMode;

    void FetchForLoop(string _FilePath, QList<QString> & amp;MatchingVe);

    void AssistAssert(QString FileName, QString QRealPath, QList<QString> & amp;MatchingVessel);


};

#endif // FDWINGS_H

cpp file

#include "Tools/FDwings.h"

Nlwingsing::Nlwingsing(QStringList DTpath,
                       QStringList KeyWord,
                       QStringList Suffix,
                       MatchingModeMcMode){
    __Init__();
    MatchPath << DTpath;
    MatchPostFix << Suffix;
    MatchKeyWord << KeyWord;
    MatchMode = McMode;
}

void Nlwingsing::setDTpath(QStringList DTpath){
    MatchPath << DTpath;

}

void Nlwingsing::setKeyWord(QStringList KeyWord){
    MatchKeyWord << KeyWord;
}

void Nlwingsing::setPostFix(QStringList Suffix){
    MatchPostFix << Suffix;
}

void Nlwingsing::setMatchMode(MatchingMode McMode){
    MatchMode = McMode;
}

QString Nlwingsing::MakePath(QString Directory){
    QRegularExpressionMatch Disk = QRegularExpression("[a-zA-Z:\.]*[\\\|/]{1}").match(Directory);
    QStringList Cap = Disk.capturedTexts();
    QString SimplePath;
    if (!Cap.isEmpty()){
        SimplePath = Cap[0];
        QStringList SplitDir = Directory.mid(SimplePath.size(), -1).split(QRegularExpression("\\|/"));
        QStringListIterator Loop(SplitDir);
        for(int wt = 0; wt < SplitDir.size(); wt + + ) {
            if (QFile(SimplePath).exists()){
                if (!SplitDir[wt].isEmpty()) QDir(SimplePath).mkpath(SplitDir[wt]);
                if (SimplePath.lastIndexOf(QRegularExpression("\\|/")){
                    SimplePath + = SplitDir[wt];
                } else {
                    SimplePath + = "\" + SplitDir[wt];
                }
            }
        }
    }
    return SimplePath;
}

QString Nlwingsing::MakeFile(QString sgFile){
    int SpecialCharC = sgFile.count(QRegularExpression("[\\|/]"));
    if (SpecialCharC > 1){
        QString CropFile = sgFile.mid(0, sgFile.lastIndexOf("\", -1));
        QFile _f(sgFile);
        if (QDir(CropFile).exists()){
            _f.open(QFile::WriteOnly);
        } else {
            MakePath(CropFile);
            _f.open(QFile::WriteOnly);
        }
        _f.close();
    }
    return sgFile;
}

void Nlwingsing::ZipGet(QString ZipPath, QString Directory, QStringList Filter){
    QZipReader Zip(ZipPath);
    QString SimpleSavePath;
    for (int i = 0; i < Zip.count(); i + + ){
        QString ZdataPath = Zip.entryInfoAt(i).filePath;
        QString BscName = QFileInfo(ZdataPath).baseName();
        if (Directory.isNull()){
            SimpleSavePath = QFileInfo(ZipPath).canonicalPath() + "/" + ZdataPath;
        } else {
            if (QFile(Directory).exists()){
                SimpleSavePath = Directory + "/" + ZdataPath;
            } else {
                SimpleSavePath = QFileInfo(ZipPath).canonicalPath() + "/" + ZdataPath;
            }
        }

        if (!Filter.isEmpty()){
            foreach(QString Fitem, Filter){
               if (BscName.contains(Fitem, Qt::CaseInsensitive)){
                    QString FolderCreate;
                    if (Zip.fileData(ZdataPath).isEmpty()){
                        continue;
                    } else {
                        FolderCreate = CombinationPath(SimpleSavePath, false);
                        MakePath(FolderCreate);
                        QFile FlterFile(CombinationPath(SimpleSavePath));
                        FlterFile.open(QIODevice::WriteOnly);
                        FlterFile.write(Zip.fileData(ZdataPath));
                        FlterFile.close();
                    }
               } else continue;
            }
        } else {
            QString FolderCreate;
            if (Zip.fileData(ZdataPath).isEmpty()){
                continue;
            } else {
                FolderCreate = CombinationPath(SimpleSavePath, false);
                MakePath(FolderCreate);
                QFile NoFlterFile(CombinationPath(SimpleSavePath));
                NoFlterFile.open(QIODevice::WriteOnly);
                NoFlterFile.write(Zip.fileData(ZdataPath));
                NoFlterFile.close();
            }
        }
    }
}

void Nlwingsing::ZipPush(QString ZipPath, QString Directory){
    QRegularExpression Tonic("[\\|/]");
    QStringList TarPath;
    QString ZipbscName;
    QString SaveFolder;
    if (Directory.isNull()){
        SaveFolder = QFileInfo(ZipPath).canonicalPath();
    } else {
        if (QFileInfo(Directory).isFile()){
            SaveFolder = CombinationPath(Directory, false);
        } else {
            if (Directory.indexOf(QRegularExpression("[a-zA-Z]\W")) != -1){
                QRegularExpression special("[:\.\\|/]");
                QStringList SplitDir = Directory.split(special).filter(QRegularExpression(".{1,}"));
                QString FirstDisk = SplitDir[0];
                SplitDir.removeFirst();
                SplitDir.insert(0, FirstDisk.append(":/"));
                SaveFolder = SplitDir.join("/");
            } else SaveFolder = QFileInfo(ZipPath).canonicalPath();
        }
        MakePath(SaveFolder);
    }
    if (QFileInfo(ZipPath).isDir()){
        setDTpath({ZipPath});
        TarPath = GetMatchingResult();
        ZipbscName = ZipPath.split(Tonic).last();
    } else {
        ZipbscName = QFileInfo(ZipPath).baseName();
        TarPath << ZipPath;
    }
    QString ZipName = CombinationPath(SaveFolder + "/" + ZipbscName + ".zip");
    QZipWriter Zwrite(ZipName);
    foreach (QString Path, TarPath){
        QString TarDirectory = Path.mid(Path.indexOf(ZipbscName), -1);
        QFile WriteFile(Path);
        WriteFile.open(QIODevice::ReadOnly);
        Zwrite.addFile(TarDirectory.toLocal8Bit(), WriteFile.readAll());
        WriteFile.close();
    }
    Zwrite.close();
}

QString Nlwingsing::CombinationPath(QString Path,bool IsretainSuffix){
    QRegularExpression Tonic("[\\|/]");
    QStringList SpSplitFd = Path.split(Tonic);
    if (!IsretainSuffix) SpSplitFd.removeLast();
    QString JoinFD = SpSplitFd.filter(QRegularExpression(".{1,}")).join("/");
    return JoinFD;
}

QStringList Nlwingsing::GetMatchingResult(){
    QStringList MatchingVe;
    foreach (QString Path, MatchPath){
        QFileInfo File(Path.simplified());
        if (File.isDir()){
            string FilePath = File.absoluteFilePath().toStdString();
            FetchForLoop(BscTgb12(FilePath.c_str()), MatchingVe);
        } else if (File.isFile()){
            string FilePath = File.canonicalPath().toStdString();
            FetchForLoop(BscTgb12(FilePath.c_str()), MatchingVe);
        } else continue;
    }
    return MatchingVe;
}

void Nlwingsing::FetchForLoop(string FilePath, QList<QString> & amp;MatchingVe){
    intptr_t Handle = 0;
    struct _finddata_t DataDetetor;
    string RealPath;
    QString QRealPath;
    string recursion;
    struct stat statc;
    recursion.assign(FilePath).append("\\*");
    Handle =_findfirst(recursion.c_str(), & amp;DataDetetor);
    if (Handle != -1){
        do{
            const char *FileName = DataDetetor.name;
            recursion.assign(FilePath).append("/").append(FileName);
            if (stat(recursion.c_str(), & statc)==0){
                if(statc.st_mode & amp; S_IFDIR){
                    if (strcmp(FileName, ".") != 0 & amp; & amp; strcmp(FileName, "..") != 0){
                        recursion.assign(FilePath).append("/").append(FileName);
                        FetchForLoop(recursion, MatchingVe);
                    }
                } else {
                    QString QFileName = QString(FileName);
                    QFileInfo FileInfo = QFileInfo(FileName);
                    QString Suffix;
                    if (FileInfo.suffix().isEmpty()){
                        Suffix = "None";
                    } else {
                        Suffix = FileInfo.suffix();
                    }
                    RealPath = Gb12TBsc(RealPath.assign(FilePath).append("/").append(FileName)).c_str();
                    QRealPath = QString(RealPath.c_str());
                    if (!MatchPostFix.isEmpty()){
                        for (auto pst = 0; pst < MatchPostFix.size(); pst + + ){
                            if (!Suffix.isEmpty() & amp; & amp;
                                Suffix.compare(MatchPostFix[pst],
                                                Qt::CaseSensitivity::CaseInsensitive) == 0){
                                if (!MatchKeyWord.isEmpty()){
                                    AssistAssert(QFileName, QRealPath, MatchingVe);
                                } else {
                                    MatchingVe.push_back(QRealPath);
                                }

                            } else {
                                if (MatchPostFix[pst].simplified().isEmpty()){
                                    MatchingVe.push_back(QRealPath);
                                } else {
                                    continue;
                                }
                            }
                        }
                    } else {
                        if (!MatchKeyWord.isEmpty()){
                            AssistAssert(QFileName, QRealPath, MatchingVe);
                        } else {
                           MatchingVe.push_back(QRealPath);
                        }
                    }
                }
            }
        } while (_findnext(Handle, & amp;DataDetetor) == 0);
        _findclose(Handle);
    }
}

void Nlwingsing::AssistAssert(QString FileName, QString QRealPath, QList<QString> & amp;MatchingVe){
    FileName = QFileInfo(FileName).baseName();
    QListIterator<QString> Iterator(MatchKeyWord);
    while (Iterator.hasNext()){
        auto spcount = 0;
        int from = 0;
        QList<int> spindex;
        QString Kword = Iterator.next();
        if (MatchMode == MatchingMode::Simple){
            for (auto kw = 0; kw < Kword.size(); kw + + ){
                int FindHandle = FileName.indexOf(Kword[kw], from, Qt::CaseInsensitive);
                if ( FindHandle != -1 & amp; & amp; spindex.count(FindHandle) == 0 ){
                    spindex.append(FindHandle);
                    from = FindHandle + 1;
                    spcount + = 1;
                }
            }
            if (spcount == Kword.size()){
                MatchingVe.push_back(QRealPath);
            }

        } else {
            if (FileName.indexOf(Kword, Qt::CaseInsensitive) == 0 ){
                MatchingVe.push_back(QRealPath);
            }
        }
    }
}

const std::string Nlwingsing::BscTgb12(const char *bcc){
   std::stringstream _slot;
    if (bcc & amp; & amp; strlen(bcc) > 1){
        int BscLenght = MultiByteToWideChar(CP_UTF8, 0, bcc, -1, NULL, 0);
        wchar_t *BscMapWc = new wchar_t[BscLenght + 1];
        memset(BscMapWc, 0, BscLenght + 1);
        MultiByteToWideChar(CP_UTF8, 0, bcc, -1, BscMapWc, BscLenght);
        int WcLenght = WideCharToMultiByte(CP_ACP, 0, BscMapWc, -1, NULL, 0, NULL, NULL);
        char *ByteC = new char[WcLenght + 1];
        memset(ByteC, 0, WcLenght + 1);
        WideCharToMultiByte(CP_ACP, 0, BscMapWc, -1, ByteC, WcLenght, NULL, NULL);
        _slot << ByteC;
        delete []BscMapWc;
        delete []ByteC;
        return _slot.str();
    } else {
        return "";
    }
};

const std::string Nlwingsing::Gb12TBsc(const string gbc){
    std::stringstream _slot;
    if (gbc.c_str() & amp; & amp; strlen(gbc.c_str()) > 1){
        //Key, the character length is calculated as the true length, excluding the trailing \0 character, so the trailing length + 1 must be added during initialization, otherwise an implicit error will be reported
        int BscLenght = MultiByteToWideChar(CP_ACP, 0, gbc.c_str(), -1, NULL, 0);
        wchar_t *BscMapWc = new wchar_t[BscLenght + 1];
        memset(BscMapWc, 0, BscLenght + 1);
        MultiByteToWideChar(CP_ACP, 0, gbc.c_str(), -1, BscMapWc, BscLenght);

        int WcLenght = WideCharToMultiByte(CP_UTF8, 0, BscMapWc, -1, NULL, 0, NULL, NULL);
        char *ByteC = new char[WcLenght + 1];
        memset(ByteC, 0, WcLenght + 1);
        WideCharToMultiByte(CP_UTF8, 0, BscMapWc, -1, ByteC, WcLenght, NULL, NULL);

        _slot << ByteC;
        delete []BscMapWc;
        delete []ByteC;
        return _slot.str();
    }else{
        return "";
    }
}

void Nlwingsing::__Init__(){
    MatchPath.clear();
    MatchPostFix.clear();
    MatchKeyWord.clear();
    MatchMode = MatchingMode::Simple;
}
Traverse folders
 Nlwingsing(QStringList DTpath traverses the directory. When there is a file in the parameter, intercept the directory to which the file belongs as the parameter
 QStringList KeyWord keyword parameter, no limit by default when empty
 QStringList Suffix file suffix, no limit by default when empty
 MatchingMode McMode = MatchingMode::Simple traversal mode,

Exact If the file name contains keywords, it will be obtained, and the character order is in order

Simple If the file name contains keywords, it will be obtained. It does not care about the character order. As long as the keyword characters are in the file name, it will be obtained.

Just set the parameters when instantiating, and then call the GetMatchingResult function to return the value.

Example:

MakePath creates folders and supports recursive folder creation,

Example

operation result

MakeFile creates a file. This function contains the Makepath code, so just put the entire path into it. If the directory does not exist, it will be created automatically

Example

operation result

ZipGet decompressed files, parameters
QString ZipPath file path
QString Directory = NULL The directory where the decompressed files are stored. The default is empty. When it is empty, the directory where the decompressed files are stored is the directory where the currently decompressed files are located. If the directory does not exist, it defaults to the directory where the files are located.
QStringList Filter = {} filter characters. This condition takes effect when the decompressed file name contains filter characters. The default is empty. When it is empty, all files will be decompressed. Otherwise, only files matching the filter characters will be obtained

Example:

Compressed file contents

Unzipped files

Directory structure preserved

ZipPush compressed files, parameters

QString ZipPath file/directory path
QString Directory = NULL The decompressed file storage directory is empty by default. If it is empty, the decompressed file storage directory will be the directory where the current decompressed file is located. If the directory does not exist, it will be automatically created.

Example:

Compress a single file

When the directory starting with a drive letter does not exist or has an incorrect format, it will be automatically corrected and created. If the drive letter does not exist, it will be placed in the directory where the file is located by default. If you are interested, you can add a correction // \ .// The code for these relative paths

operation result

Compressed folder

Test folder contents

Put it in the current directory and take a file directory that does not exist

operation result

hierarchical structure preserved