Qt压缩解压文件夹

1、在.pro文件中添加 gui-private

2、压缩代码

int FileApi::compressDir(QZipWriter &zipWriter, QString floder, QString parentFolder)
{
    QTextCodec *codec = QTexCodec::codecForName("GB2312");
    if(codec != NULL)
    {
        QTextCodec::setCodecForLocal(codec);
    {
    int ret = 0;
    
    QDir folderDir(folderPath);
    QStringList files = folderDir.entryList(QDir::Files);
    QStringList folders = folderDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach(const QString &file, files)
    {
        QString filePath = folderPath + "\\" + file;
        QString zipFilePath = (parentFolder.isEmpty()?"":parentFolder+"\\")+file;

        QFile fileRead(filePath);
        if(!fileRead.open(QIODevice::ReadOnly))
        {
            return -1;
        }
        QByteArray fileData = fileRead.readAll();

        fileRead.close();
        zipWriter.addFile(zipFilePath, fileData);
    }

    foreach(const QString &folder, folders)
    {
        QString subFolderPath = folderPath + "\\" + folder;
        QString zipFolderPath = (parentFolder.isEmpty()?"":parentFolder + "\\") +folder;
        QByteArray dt = zipFolderPath.toLocal8Bit();
        QString folderTemp = QString::fromLocal8Bit(dt);
        zipWriter.addDirectory(folderTemp);
        compressDir(zipWriter, subFolderPath, folderTemp);
    }

    return ret;
}

    

3、解压代码

int FileApi::decompress(QZipReader &zipReader, QString folderPath)
{
    int ret = 0;
    QVector fileList = zipReader.fileInfoList();
    QFileInfoList fileInfoList;
    foreach(QZipReader::FileInfo info, fileList)
    {
        QString path = folderPath + "/" + info.filePath;
        if(info.isDir())
        {
            QDir dir(path);
            if(!dir.exists())
            {    
                dir.mkpath(".");    
            }
        }
        else if(info.isFile)
        {
            QFile file(path);
            if(!file.open(QIODevice::WriteOnly))
            { 
                return -1;   
             }
            QByteArray dt = info.filePath.toUtf8();
            QString pathTemp = QString::fromLocal8Bit(dt);
            QByteArray fileData = zipReader.fileData(pathTemp);
            file.write(fileData);
            file.close();
        }
    }
    return ret;
}

 

你可能感兴趣的:(qt,开发语言)