QT 本地文件搜索、创建文件/文件夹、文件/目录解压缩

上代码:

头文件

#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> &MatchingVe);

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


};

#endif // FDWINGS_H

cpp文件

#include "Tools/FDwings.h"

Nlwingsing::Nlwingsing(QStringList DTpath,
                       QStringList KeyWord,
                       QStringList Suffix,
                       MatchingMode McMode){
    __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.size() - 1){
                    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> &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(), &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 & S_IFDIR){
                    if (strcmp(FileName, ".") != 0 && 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() &&
                                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, &DataDetetor) == 0);
        _findclose(Handle);
    }
}

void Nlwingsing::AssistAssert(QString FileName, QString QRealPath, QList<QString> &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 && 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 && 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() && strlen(gbc.c_str()) > 1){
        //关键,字符长度计算为真是长度,不包括结尾\0符,因此初始化时要加上结尾长度+1,否则隐性报错
        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;
}
遍历文件夹
               Nlwingsing(QStringList DTpath        遍历的目录,当参数里有文件时,截取该文件所属目录作为参数
               QStringList KeyWord        关键字参数, 为空时默认不限制
               QStringList Suffix         文件后缀, 为空时默认不限制
               MatchingMode McMode = MatchingMode::Simple        遍历模式,

exact 文件名包含关键字则获取,字符顺序有序

  simple  文件名包含关键字则获取,不在乎字符顺序,只要关键字字符都在文件名中就获取

实例化的时候把参数设置好,然后调用 GetMatchingResult 函数返回值就行了

实例:

        

MakePath 创建文件夹,支持递归创建文件夹,

实例

运行结果

MakeFile 创建文件,该函数是包含Makepath代码的,所以直接把整个路径放进去就行了,目录不存在会自动创建

实例

运行结果

ZipGet 解压文件,参数
QString ZipPath                文件路径
QString Directory = NULL       解压的文件存放目录,默认为空,为空时解压文件存放目录为当前解压文件所在目录,目录不存在时默认解压到文件所在目录
QStringList Filter = {}        过滤字符,解压文件文件名包含过滤字符时,该条件生效,默认为空,为空时解压所有文件,反之只获取过滤字符所匹配的文件

实例:

压缩文件内容

解压后的文件

保留了目录结构

ZipPush 压缩文件,参数

QString ZipPath                文件/目录路径
QString Directory = NULL       解压的文件存放目录,默认为空,为空时解压文件存放目录为当前解压文件所在目录,目录不存在时自动创建

实例:

压缩单个文件

当带有盘符开头的目录不存在或格式错误时,自动纠正并创建,不存在盘符时就默认放到文件所在目录下,有兴趣的可以加一下纠正 //  \\ .// 这些相对路径的代码

运行结果

压缩文件夹

测试文件夹内容

放到当前目录下吧,取一个不存在的文件目录

运行结果

保留了层级结构

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值