void OpticPack::loadAssets() const { ZIPENTRY ze; if(GetZipItem(handle, -1, &ze) != ZR_OK) { throw OpticPackException("Blah"); } for(int i = 0, j = ze.index; i < j; i++) { if(GetZipItem(handle, i, &ze) != ZR_OK) { throw OpticPackException("Blah"); } if(ze.attr & FILE_ATTRIBUTE_DIRECTORY) { continue; } std::string audio_t = "audio/"; std::string images_t = "images/"; if(std::string(ze.name).compare(0, audio_t.length(), audio_t) == 0) { auto ret = fetchFile<audioBin>(handle, ze.name); OpticAudio file = make_pair(ret.first, move(ret.second)); audio[ze.name] = file; } else if(std::string(ze.name).compare(0, images_t.length(), images_t) == 0) { auto ret = fetchFile<imageBin>(handle, ze.name); OpticImage file = make_pair(ret.first, move(ret.second)); images[ze.name] = file; } } }
void UnzipWithProgress(const TCHAR *zipfn, HWND hprog) { HZIP hz = OpenZip(zipfn,0); ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numentries=ze.index; // first we retrieve the total size of all zip items DWORD tot=0; for (int i=0; i<numentries; i++) {GetZipItem(hz,i,&ze); tot+=ze.unc_size;} // DWORD countall=0; // this is our progress so far for (int i=0; i<numentries && !abort_p; i++) { GetZipItem(hz,i,&ze); // We'll unzip each file bit by bit, to a file on disk char fn[1024]; wsprintf(fn,"\\z\\%s",ze.name); HANDLE hf = CreateFile(fn,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); char buf[16384]; // Each chunk will be 16k big. After each chunk, we show progress DWORD countfile=0; for (ZRESULT zr=ZR_MORE; zr==ZR_MORE && !abort_p; ) // nb. the global "abort_p" flag is set by the user clicking the Cancel button. { zr=UnzipItem(hz,i,buf,16384); unsigned long bufsize=16384; if (zr==ZR_OK) bufsize=ze.unc_size-countfile; // bufsize is how much we got this time DWORD writ; WriteFile(hf,buf,bufsize,&writ,0); countfile+=bufsize; // countfile counts how much of this file we've unzipped so far countall+=bufsize; // countall counts how much total we've unzipped so far // Now show progress, and let Windows catch up... int i = (int)(100.0*((double)countall)/((double)tot)); SendMessage(hprog,PBM_SETPOS,i,0); PumpMessages(); } CloseHandle(hf); if (abort_p) DeleteFile(fn); } CloseZip(hz); }
bool CZipObj::UnZipFile(CString strZipPath, CString strUnzipPath) { USES_CONVERSION; int nPos = strZipPath.ReverseFind('.'); CString strPath = strZipPath.Left(nPos); //.zip strZipPath.GetLength() - 4 if (strUnzipPath != "") strPath = strUnzipPath; std::string strUtf8Path = CMyCodeConvert::Gb2312ToUtf8(T2A(strPath)); try { Poco::File p(strUtf8Path); //T2A(strPath) if (p.exists()) p.remove(true); } catch (Poco::Exception) { } HZIP hz = OpenZip(strZipPath, _strPwd.c_str()); ZIPENTRY ze; GetZipItem(hz, -1, &ze); int numitems = ze.index; SetUnzipBaseDir(hz, strPath); for (int i = 0; i < numitems; i++) { GetZipItem(hz, i, &ze); UnzipItem(hz, i, ze.name); } CloseZip(hz); return true; }
void CAppManager::ReloadRhoBundle(const char* szUrl, const char* szZipPassword) { if ( szUrl ) { //get zip file with rhodes DWORD dwDataSize = 0; char* zipData = remote_data( L"GET", const_cast<char*>(szUrl), NULL, 0, false, true, false, &dwDataSize ); LPWSTR rootw = wce_mbtowc(RhoGetRootPath()); //TODO: Add error handling if ( zipData && dwDataSize > 0 ) { ZIPENTRY ze; // Open zip file HZIP hz = OpenZip(zipData, dwDataSize, szZipPassword); if ( hz ) { //Stop HTTP Server CHttpServer::Instance()->FreezeThread(); // Set base for unziping SetUnzipBaseDir(hz, rootw); // Get info about the zip // -1 gives overall information about the zipfile GetZipItem(hz,-1,&ze); int numitems = ze.index; // Iterate through items and unzip them for (int zi = 0; zi<numitems; zi++) { // fetch individual details, e.g. the item's name. GetZipItem(hz,zi,&ze); // unzip item UnzipItem(hz, zi, ze.name); } CloseZip(hz); //Show MessageBox MessageBox(NULL, _T("Rhobundle has been updated successfully.\n\nPlease restart application."), _T("Information"), MB_OK | MB_ICONINFORMATION ); } } if ( rootw ) free(rootw); if ( zipData ) delete zipData; } }
char * unziplib_c::getFileName(int i) { ZIPENTRY ze; GetZipItem(hz,i,&ze); char * temp = new char[strlen(ze.name)+1]; memcpy(temp, ze.name, strlen(ze.name)+1); return temp; }
bool CDlgView::UnZipFile(string unzipfilename,string zipfilepath) { HZIP hz; //DWORD writ; // EXAMPLE 2 - unzip it with the names suggested in the zip hz = OpenZip(unzipfilename.c_str(),0); string path = zipfilepath +"\\"; SetUnzipBaseDir(hz,path.c_str()); ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numitems=ze.index; for (int zi=0; zi<numitems; zi++) { GetZipItem(hz,zi,&ze); UnzipItem(hz,zi,ze.name); } CloseZip(hz); return true; }
int main() { HZIP hz; hz = CreateZip("std1.zip",0); ZipAdd(hz,"znsimple.jpg", "std_sample.jpg"); ZipAdd(hz,"znsimple.txt", "std_sample.txt"); CloseZip(hz); hz = OpenZip("std1.zip",0); ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numitems=ze.index; for (int zi=0; zi<numitems; zi++) { GetZipItem(hz,zi,&ze); UnzipItem(hz,zi,ze.name); } CloseZip(hz); return 0; }
BOOL CMyUtility::UnZip( LPCTSTR wcPathIn, LPCTSTR wcExtractObject, LPCTSTR wcPathOut ) { HZIP hz; int index, numfile; ZIPENTRYW ze = {0}; TCHAR wcFilePath[MAX_PATH] = {0}; if(!wcPathIn) return FALSE; hz = OpenZip((void*)wcPathIn, 0, ZIP_FILENAME); if (!hz) return FALSE; GetZipItem(hz, -1, &ze); numfile = ze.index; for(index = 0; index < numfile; index++) { GetZipItem(hz, index, &ze); if (!wcExtractObject) { swprintf(wcFilePath, MAX_PATH - 1, _T("%s\\%s"), wcPathOut, ze.name); UnzipItem(hz, index, wcFilePath, 0, ZIP_FILENAME); } else { int len = lstrlen(wcExtractObject); if (_tcsnicmp(wcExtractObject, ze.name, len) == 0) { swprintf(wcFilePath, MAX_PATH - 1, _T("%s\\%s"), wcPathOut, ze.name); UnzipItem(hz, index, wcFilePath, 0, ZIP_FILENAME); //check to know object need to be extracted is file if (!(ze.attr & FILE_ATTRIBUTE_DIRECTORY) && len == lstrlen(ze.name)) break; } } } CloseZip(hz); return TRUE; return TRUE; }
int unziplib_c::extractFile(char * fName, char * fFile) { ZIPENTRY ze; int itemCount = getCount(); for (int i=0; i<itemCount; i++) { GetZipItem(hz,i,&ze); if (strcmp(ze.name, fName) == 0) { UnzipItem(hz,i,fFile); i = itemCount; } } return 0; }
int rho_unzip_file(const char* szZipPath) { #ifdef UNICODE rho::StringW strZipPathW; rho::common::convertToStringW(szZipPath, strZipPathW); HZIP hz = OpenZipFile(strZipPathW.c_str(), ""); if ( !hz ) return 0; // Set base for unziping SetUnzipBaseDir(hz, rho::common::convertToStringW(RHODESAPPBASE().getDBDirPath()).c_str() ); #else HZIP hz = OpenZipFile(szZipPath, ""); if ( !hz ) return 0; // Set base for unziping SetUnzipBaseDir(hz, RHODESAPPBASE().getDBDirPath().c_str() ); #endif ZIPENTRY ze; ZRESULT res = 0; // Get info about the zip // -1 gives overall information about the zipfile res = GetZipItem(hz,-1,&ze); int numitems = ze.index; // Iterate through items and unzip them for (int zi = 0; zi<numitems; zi++) { // fetch individual details, e.g. the item's name. res = GetZipItem(hz,zi,&ze); if ( res == ZR_OK ) res = UnzipItem(hz, zi, ze.name); } CloseZip(hz); return res == ZR_OK ? 1 : 0; }
void FileUtils::Unzip(std::string& source, std::string& destination, UnzipCallback callback, void *data) { std::wstring wideSource = UTILS_NS::UTF8ToWide(source); std::wstring wideDestination = UTILS_NS::UTF8ToWide(destination); HZIP handle = OpenZip(wideSource.c_str(), 0); SetUnzipBaseDir(handle, wideDestination.c_str()); ZIPENTRY zipEntry; ZeroMemory(&zipEntry, sizeof(ZIPENTRY)); GetZipItem(handle, -1, &zipEntry); int numItems = zipEntry.index; if (callback != NULL) { std::ostringstream message; message << "Starting extraction of " << numItems << " items from " << source << "to " << destination; std::string messageString = message.str(); callback((char*) messageString.c_str(), 0, numItems, data); } for (int zi = 0; zi < numItems; zi++) { ZeroMemory(&zipEntry, sizeof(ZIPENTRY)); GetZipItem(handle, zi, &zipEntry); if (callback != NULL) { std::string name = WideToUTF8(zipEntry.name); std::string message = "Extracting "; message.append(name); message.append("..."); callback((char*) message.c_str(), zi, numItems, data); } UnzipItem(handle, zi, zipEntry.name); } CloseZip(handle); }
int unziplib_c::unzipall(char * aFolder) { ZIPENTRY ze; char * path = new char[MAX_PATH]; memcpy(path,aFolder,strlen(aFolder)+1); int itemCount = getCount(); for (int i=0; i<itemCount; i++) { GetZipItem(hz,i,&ze); memcpy(path+strlen(aFolder),ze.name,strlen(ze.name)+1); UnzipItem(hz,i,path); } delete[] path; return 0; }
bool unzipPatchFile( void ) { #if defined(Q_WS_WIN) QString f = DEFAULT_UPGRADE_FILE_NAME; HZIP hz = OpenZip( (void *)f.toStdWString().c_str(), 0, ZIP_FILENAME ); if( !hz ) return false; do{ ZIPENTRYW ze; ZRESULT zr = GetZipItem( hz, -1, &ze ); if( zr != ZR_OK ) { qDebug() << "unzipPatchFile failed : " << zr; break; } int numitems = ze.index; for( int i = 0; i < numitems; i++ ) { GetZipItem( hz, i, &ze ); qDebug() << "unzipPatchFile" << ze.name; UnzipItem( hz, i, ze.name, 0, ZIP_FILENAME ); } } while( false ); CloseZip(hz); QFile::remove( DEFAULT_UPGRADE_FILE_NAME ); #else // TODO : other platform(MacOS) unzip patch file #endif return false; }
void ZipArchive::UnzipThreadFunc(const std::string& zip, const std::string& target, UnzipDoneCallback callback, void* cbUserdata) { LogInfo() << "Unzipping file: " << zip; HZIP hz = OpenZip((void *)zip.c_str(), 0, ZIP_FILENAME); if(!hz) { LogWarn() << "Failed to open Zip-File: " << zip; return; } // Get last entry ZIPENTRY ze; ZRESULT zr = GetZipItem(hz, -1, &ze); if (zr == ZR_OK) { int numItems = ze.index; LogInfo() << " - Found " << numItems << " items in ZipFile"; for(int i=0;i<numItems;i++) { GetZipItem(hz, i, &ze); std::string t = target + "\\" + ze.name; LogInfo() << " - Unzipping file to: " << t;; UnzipItem(hz, i, (void *)t.c_str(), 0, ZIP_FILENAME); callback(zip, cbUserdata, i, numItems); } } CloseZip(hz); }
/** unzips the given archive */ XRESULT ZipArchive::Unzip(const std::string& zip, const std::string& target) { LogInfo() << "Unzipping file: " << zip; HZIP hz = OpenZip((void *)zip.c_str(), 0, ZIP_FILENAME); if(!hz) { LogWarn() << "Failed to open Zip-File: " << zip; return XR_FAILED; } // Get last entry ZIPENTRY ze; ZRESULT zr = GetZipItem(hz, -1, &ze); if (zr == ZR_OK) { int numItems = ze.index; LogInfo() << " - Found " << numItems << " items in ZipFile"; for(int i=0;i<numItems;i++) { GetZipItem(hz, i, &ze); std::string t = target + "\\" + ze.name; LogInfo() << " - Unzipping file to: " << t;; UnzipItem(hz, i, (void *)t.c_str(), 0, ZIP_FILENAME); } } CloseZip(hz); return XR_SUCCESS; }
QString ClassSpaceChecker::unzipFile(const QString &jarPath, const ClassFileContext *ctx) { QString output; bool ok = false; #if defined(Q_WS_WIN) QString f = jarPath; HZIP hz = OpenZip( (void *)f.toStdWString().c_str(), 0, ZIP_FILENAME ); if( !hz ) { QMessageBox::warning(this, "", tr("Jar file not found.")); ui.comboBox_JarFile->setFocus(); return ""; } do{ ZIPENTRYW ze; ZRESULT zr = GetZipItem( hz, -1, &ze ); if( zr != ZR_OK ) break; int i; zr = FindZipItem(hz, ctx->filePath.toStdWString().c_str(), true, &i, &ze); if( zr != ZR_OK ) break; //QString output = generateFileTempPath() + "Temp.class"; output = generateFileTempPath() + ctx->fullClassNameForKey + (ctx->javaFileFlag ? ".java" : ".class"); zr = UnzipItem(hz, i, (void*)output.toStdWString().c_str(), 0, ZIP_FILENAME); if( zr != ZR_OK ) break; ok = true; } while( false ); CloseZip(hz); #else // TODO : other platform(MacOS) unzip patch file return false; #endif if(ok) return output; return ""; }
// CPropertiesFiles 訊息處理常式 BOOL CPropertiesFiles::OnInitDialog() { CPropertyPage::OnInitDialog(); HZIP hZip; ZIPENTRY ze; CARMDlg* dlg=(CARMDlg*)this->GetParentOwner()->GetParent(); arfile* arFile=(arfile*)dlg->m_lstFiles.GetItemDataPtr(dlg->m_lstFiles.GetCurSel()); hZip=OpenZip(arFile->fileName,0,ZIP_FILENAME); if (hZip) { for (int c=0; GetZipItem(hZip,c,&ze)!=ZR_ARGS; c++) { if (ze.name[_tcslen(ze.name)-1]!='/') ((CListBox*)this->GetDlgItem(IDC_PROP_FILELIST))->AddString(ze.name); } CloseZip(hZip); } return FALSE; }
bool findPackageFromEmbeddedZip(wchar_t* buf, DWORD cbSize) { bool ret = false; CResource zipResource; if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { return false; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { return false; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); ZRESULT zr; int index = 0; do { ZIPENTRY zentry; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } if (wcsstr(zentry.name, L"nupkg")) { ZeroMemory(buf, cbSize); int idx = wcscspn(zentry.name, L"-"); memcpy(buf, zentry.name, sizeof(wchar_t) * idx); ret = true; break; } index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); return ret; }
bool CZip::extract(const QString & filePath, const QString & extDirPath, const QString & singleFileName, const QString &password) { HZIP hz = OpenZip(filePath.toStdString().c_str(), password.isEmpty() ? 0 : password.toStdString().c_str()); if(!hz) { return false; } SetUnzipBaseDir(hz,extDirPath.toStdString().c_str()); if (!singleFileName.isEmpty()) { ZIPENTRY ze; int i; FindZipItem(hz, singleFileName.toStdString().c_str(), true, &i, &ze); UnzipItem(hz, i, ze.name); CloseZip(hz); return true; } for (int i = 0; ;i++) { ZIPENTRY ze; ZRESULT zr = GetZipItem(hz, i, &ze); if (zr != ZR_OK) { if(zr == ZR_FAILED || zr == ZR_NOTFOUND) { CloseZip(hz); return false; } break; // no more } UnzipItem(hz, i, ze.name); } CloseZip(hz); return true; }
static BOOL unzip(HZIP zipf, int nitems, IProgressDialog *pd) { int i = 0; ZRESULT res; ZIPENTRYW ze; for (i = 0; i < nitems; i++) { res = GetZipItem(zipf, i, &ze); if (res != ZR_OK) { show_zip_error(L"Failed to get zip item", L"", res); return false;} res = UnzipItem(zipf, i, ze.name, 0, ZIP_FILENAME); if (res != ZR_OK) { CloseZip(zipf); show_zip_error(L"Failed to extract zip item (is your disk full?):", ze.name, res); return false;} pd->SetLine(2, ze.name, true, NULL); pd->SetProgress(i, nitems); } CloseZip(zipf); return true; }
static BOOL extract(LPVOID cdata, DWORD csz) { HANDLE h; WCHAR tempnam[MAX_PATH+1] = {0}; BOOL ret = true; HZIP zipf; ZIPENTRYW ze; ZRESULT res; int nitems; HRESULT hr; IProgressDialog *pd = NULL; hr = CoCreateInstance(CLSID_ProgressDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pd)); if (FAILED(hr)) { show_error(L"Failed to create progress dialog"); return false; } pd->SetTitle(L"Extracting Calibre Portable"); pd->SetLine(1, L"Decompressing data...", true, NULL); h = temp_file(tempnam); if (h == INVALID_HANDLE_VALUE) return false; pd->StartProgressDialog(NULL, NULL, PROGDLG_NORMAL | PROGDLG_AUTOTIME | PROGDLG_NOCANCEL, NULL); if (!decompress(cdata, csz, h, pd)) { ret = false; goto end; } SetFilePointer(h, 0, NULL, FILE_BEGIN); zipf = OpenZip(h, 0, ZIP_HANDLE); if (zipf == 0) { show_last_error(L"Failed to open zipped portable data"); ret = false; goto end; } res = GetZipItem(zipf, -1, &ze); if (res != ZR_OK) { show_zip_error(L"Failed to get count of items in portable data", L"", res); ret = false; goto end;} nitems = ze.index; pd->SetLine(1, L"Copying files...", true, NULL); if (!unzip(zipf, nitems, pd)) { ret = false; goto end; } end: pd->StopProgressDialog(); pd->Release(); CloseHandle(h); DeleteFile(tempnam); return ret; }
DWORD WINAPI decompress(LPVOID lpParam) { //Open struct and set variables PMYDATA pDataArray = (PMYDATA)lpParam; //Open the struct char *infilename = pDataArray -> para_infilename; //Get input file name char *outfilename = pDataArray -> para_outfilename; //Get output file name char *password = pDataArray -> para_password; //Get password LPRDATA rdPtr = pDataArray -> para_rdPtr; //Get rdPtr //Set non-struct variables & begin extraction HZIP hz = OpenZip(infilename,0); //0 = no password SetUnzipBaseDir(hz,outfilename); //Set the extract-to folder ZIPENTRY baseze; ZRESULT zr = GetZipItem(hz,-1,&baseze); //ZRESULT zr contains error number. //This part may get complicated. //No error with no password, so just extract for (int zi=0; zi<baseze.index; zi++) { ZIPENTRY ze; GetZipItem(hz,zi,&ze); // fetch individual details zr=UnzipItem(hz, zi, ze.name); // e.g. the item's name. } CloseZip(hz); if (zr==ZR_OK) { rdPtr->rRd->PushEvent(0); NoCurrentCompression=true; PasswordBeingUsed=false; } else { //Error occured when extracting with no password if (zr==ZR_PASSWORD&&password!="0") { //ZR_PASSWORD -> invalid password. So try with password, if one is provided. zr = ZR_OK; CloseZip(hz); hz = OpenZip(infilename,password); GetZipItem(hz,-1,&baseze); NumberOfFilesExtracted=baseze.index; MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\"", "Debug", NULL); PasswordBeingUsed=true; //No error when extracting with given password, so just extract. for (int zi=0; zi<baseze.index; zi++) { //I Can Haz Stallage ZIPENTRY ze; GetZipItem(hz,zi,&ze); // fetch individual details zr=UnzipItem(hz, zi, ze.name); // e.g. the item's name. } CloseZip(hz); NoCurrentCompression=true; if (zr==ZR_OK) { rdPtr->rRd->PushEvent(0); MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\" > zr==ZR_OK", "Debug", NULL); } else { if (zr==ZR_PASSWORD) { //The password provided was wrong, so report it. returnstring="Password incorrect or required."; MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\" > zr==ZR_PASSWORD", "Debug", NULL); rdPtr->rRd->PushEvent(1); } else { //Password was correct but error occured anyway MessageBox(NULL,"zr==ZR_PASSWORD&&password!=\"0\" > zr!=ZR_PASSWORD", "Debug", NULL); stringstream temp; temp<<"An error occured, but the provided password was correct. Error number "<<zr<<"."; returnstring=temp.str(); NoCurrentCompression=true; rdPtr->rRd->PushEvent(1); } } } else { //Not a password error when we tried to open without a password... stringstream temp; temp<<"An error occured - not a password error. Error number "<<zr<<"."; returnstring=temp.str(); NoCurrentCompression=true; rdPtr->rRd->PushEvent(1); } } //FormatZipMessage(zr,LastFileExtracted,sizeof(LastFileExtracted)); return 0; }
void* StartStage_AutoPatch::unzipPatchThread(void* ptr) { StartStage_AutoPatch* pkThisObj = static_cast<StartStage_AutoPatch*>(ptr); LOGD("[StartStage_AutoPatch] CopyResThread()"); HZIP pZipHandle = 0; //设置zip工作路径 //直接从文件打开zip包 pthread_mutex_lock (&ms_kStringMutex); const string& strZipFile_1 = pkThisObj->getCurrentUnzipFile(); pthread_mutex_unlock(&ms_kStringMutex); struct timespec kDelay = {0}; kDelay.tv_sec = 2; kDelay.tv_nsec = 0; //pthread_delay_np(&kDelay); pZipHandle = OpenZip(strZipFile_1.c_str(), 0); if (!pZipHandle) { WriteConErr("Can't find zip file!\n"); return 0; } //确保zip包会被关闭 struct ZipGuard { ZipGuard() { } ZipGuard(HZIP in_handle) : handle(in_handle) { } ~ZipGuard() { CloseZip(handle); } HZIP handle; } zip_guard(pZipHandle); //查询zip包条目 ZIPENTRY kZipEntry = { 0 }; if (ZR_OK != GetZipItem(pZipHandle, -1, &kZipEntry)) { pkThisObj->__logErr("GetZipItem() to query entry count failed\r\n"); return 0; } char szInfo[200] = ""; int nMaxIndex = kZipEntry.index; sprintf(szInfo, "zip has %d items\r\n", kZipEntry.index); pkThisObj->__log(szInfo); #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) string strDestPath = SDCARD_GAME_NAME_SLASH; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) string strDestPath = "../"; #endif //逐个解压 int nUnzipCount = 0; for (int nZipIndex = 0; nZipIndex < nMaxIndex; nZipIndex++) { ZIPENTRY kTempZipEntry = { 0 }; GetZipItem(pZipHandle, nZipIndex, &kTempZipEntry); string strDestFileName = strDestPath + string(kTempZipEntry.name); //解压 if (ZR_OK != UnzipItem(pZipHandle, nZipIndex, strDestFileName.c_str())) { char szInfo[500] = ""; sprintf(szInfo, "UnzipItem failed: %s -> %s\r\n", kTempZipEntry.name, strDestFileName.c_str()); WriteConErr(szInfo); CloseZip(pZipHandle); } } CloseZip(pZipHandle); remove(strZipFile_1.c_str()); WriteCon("Unzip %s succeeded!\n", strZipFile_1.c_str()); pkThisObj->beginDownload(); return 0; }
/////////////////////////////////////////////////////////////////////////////// // OnTest void CXZipTestDlg::OnTest() { #ifdef _UNICODE ZIPENTRYW ze; #else ZIPENTRY ze; #endif memset(&ze, 0, sizeof(ze)); TCHAR * pszArchive1 = _T("_TestZipTmp1.zip"); TCHAR * pszArchive2 = _T("_TestZipTmp2.zip"); // text files TCHAR * pszName1 = _T("_TestZipTmp1.txt"); TCHAR * pszName2 = _T("_TestZipTmp2.txt"); TCHAR * pszName3 = _T("_TestZipTmp3.txt"); // binary files TCHAR * pszName4 = _T("_TestZipTmp4.bin"); TCHAR * pszName5 = _T("_TestZipTmp5.bin"); TCHAR * pszName6 = _T("_TestZipTmp6.bin"); TCHAR * pszName7 = _T("_TestZipTmp7.bin"); TCHAR * pszName8 = _T("_TestZipTmp8.bin"); TCHAR * pszName9 = _T("_TestZipTmp9.bin"); // delete zip files ::DeleteFile(pszArchive1); ::DeleteFile(pszArchive2); // create .txt files CreateTextFile(pszName1, 10000); CreateTextFile(pszName2, 100); CreateTextFile(pszName3, 10); // create .bin files CreateBinaryFile(pszName4, 16384); CreateBinaryFile(pszName5, 3*16384); CreateBinaryFile(pszName6, 8*16384); CreateBinaryFile(pszName7, 123); CreateBinaryFile(pszName8, 17000); CreateBinaryFile(pszName9, 8*16384+1); /////////////////////////////////////////////////////////////////////////// // single-file zip m_List.AddLine(CXListBox::Blue, CXListBox::White, _T("")); m_List.Printf(CXListBox::Navy, CXListBox::White, 0, _T(" === Testing single-file zip ===")); BOOL bRet = Zip(pszArchive1, pszName1); if (bRet) { m_List.Printf(CXListBox::Green, CXListBox::White, 0, _T(" Zip archive created OK")); m_List.Printf(CXListBox::Black, CXListBox::White, 0, _T(" === Testing unzip ===")); HZIP hz = OpenZip(pszArchive1, 0, ZIP_FILENAME); if (hz) { ZRESULT zr = GetZipItem(hz, -1, &ze); if (zr == ZR_OK) { int numitems = ze.index; if (numitems == 1) { m_List.Printf(CXListBox::Green, CXListBox::White, 0, _T(" Zip archive contains 1 file ==> OK")); VerifyZip(hz, pszName1); CloseZip(hz); } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Zip contents bad")); } } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" GetZipItem failed")); } } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Failed to open zip file '%s'"), pszArchive1); } } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Failed to create zip")); } /////////////////////////////////////////////////////////////////////////// // multi-file zip m_List.AddLine(CXListBox::Blue, CXListBox::White, _T("")); m_List.Printf(CXListBox::Navy, CXListBox::White, 0, _T(" === Testing multi-file zip ===")); HZIP hz = CreateZip(pszArchive2, 0, ZIP_FILENAME); if (hz) { m_List.Printf(CXListBox::Green, CXListBox::White, 0, _T(" Zip archive created OK")); if ((ZipAdd(hz, pszName1, pszName1, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName2, pszName2, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName3, pszName3, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName4, pszName4, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName5, pszName5, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName6, pszName6, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName7, pszName7, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName8, pszName8, 0, ZIP_FILENAME) == ZR_OK) && (ZipAdd(hz, pszName9, pszName9, 0, ZIP_FILENAME) == ZR_OK)) { m_List.Printf(CXListBox::Green, CXListBox::White, 0, _T(" Files added to zip archive OK")); CloseZip(hz); hz = OpenZip(pszArchive2, 0, ZIP_FILENAME); if (hz) { m_List.Printf(CXListBox::Green, CXListBox::White, 0, _T(" Zip archive opened OK")); GetZipItem(hz, -1, &ze); int numitems = ze.index; if (numitems == 9) { m_List.Printf(CXListBox::Green, CXListBox::White, 0, _T(" Zip archive contains correct number of entries")); for (int i = 0; i < numitems; i++) { GetZipItem(hz, i, &ze); m_List.Printf(CXListBox::Black, CXListBox::White, 0, _T(" %d: %s"), i, ze.name); } VerifyZip(hz, pszName1); VerifyZip(hz, pszName2); VerifyZip(hz, pszName3); VerifyZip(hz, pszName4); VerifyZip(hz, pszName5); VerifyZip(hz, pszName6); VerifyZip(hz, pszName7); VerifyZip(hz, pszName8); VerifyZip(hz, pszName9); } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Number of entries in zip archive is incorrect")); } } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Failed to open zip archive")); } } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Failed to add file to zip archive")); } } else { m_List.Printf(CXListBox::Red, CXListBox::White, 0, _T(" Failed to create zip archive")); } CloseZip(hz); // the files are not deleted - you can inspect them after running test //::DeleteFile(pszArchive1); //::DeleteFile(pszArchive2); //::DeleteFile(pszName1); //::DeleteFile(pszName2); //::DeleteFile(pszName3); m_List.AddLine(CXListBox::Blue, CXListBox::White, _T("")); }
DWORD DecompressManager::deCompressProc_(LPVOID lpParameter) { DecompressManager* self = (DecompressManager*)lpParameter; TCHAR* sourceFileName = FileInfo::getInstance().getSourceFileName(); TCHAR* targetDir = FileInfo::getInstance().getTargetFileName(); if (sourceFileName == NULL) { self->decompressDelegate_->decompressError(SOURCE_FILE_PATH_ERROR); return 0; } if (targetDir == NULL) { self->decompressDelegate_->decompressError(TARGET_DIR_PATH_ERROR); return 0; } HZIP hz = OpenZip(sourceFileName,0); if (hz == NULL) { self->decompressDelegate_->decompressError(OPEN_ZIP_FILE_ERROR); return 0; } TCHAR appDir[MAX_PATH]; wcscpy(appDir, targetDir); wcscat(appDir, L"F33APP\\"); self->deleteDirectory_(appDir); ZIPENTRY ze; if (GetZipItem(hz,-1,&ze) != ZR_OK) { self->decompressDelegate_->decompressError(GET_ZIP_HEAD_ERROR); return 0; } DWORD numitems=ze.index; long unzipSize = ze.unc_size; for (int zi=0; zi<numitems; zi++) { ZIPENTRY ze; if (GetZipItem(hz,zi,&ze) != ZR_OK) // fetch individual details { self->decompressDelegate_->decompressError(GET_ZIP_ITEM_ERROR); return 0; } unzipSize += ze.unc_size; } ULARGE_INTEGER freeBytesAvailableToCaller; ULARGE_INTEGER totalNumberOfBytes; ULARGE_INTEGER totalNumberOfFreeBytes; #define RESERVED_SPACE 1024*1024 if (GetDiskFreeSpaceEx(targetDir, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes)) { if (freeBytesAvailableToCaller.QuadPart < (unzipSize + RESERVED_SPACE)) { self->decompressDelegate_->decompressError(NO_ENOUGH_SPACE_ERROR); CloseZip(hz); return 0; } } else { self->decompressDelegate_->decompressError(NO_ENOUGH_SPACE_ERROR); CloseZip(hz); return 0; } self->decompressDelegate_->updateZipInfo(numitems); for (int zi=0; zi<numitems; zi++) { ZIPENTRY ze; if (GetZipItem(hz,zi,&ze) != ZR_OK) // fetch individual details { self->decompressDelegate_->decompressError(GET_ZIP_ITEM_ERROR); return 0; } TCHAR tempPath[MAX_PATH] = {0}; wcscpy(tempPath, targetDir); wcscat(tempPath, ze.name); self->replace_(tempPath); DWORD unzipResult = UnzipItem(hz, zi, tempPath); if (unzipResult != ZR_OK) // e.g. the item's name. { self->decompressDelegate_->decompressError(UNZIP_PROC_ERROR); return 0; } self->decompressDelegate_->updateStep(ze.name); int lastPostion = wcslen(ze.name)-1; if ((ze.name[lastPostion] != L'\\') && (ze.name[lastPostion] != L'/')) { //处理一下,使MAP的KEY和JSON的KEY一致 TCHAR keyName[MAX_PATH] = {0}; wcscpy(keyName, ze.name); self->replace_(keyName); self->fileContainer_[keyName] = tempPath; } } CloseZip(hz); if (self->checkFlag_) { self->checkMd5(); } self->decompressDelegate_->decompressFinish(); return 0; }
bool unziplib_c::isDir(int i) { ZIPENTRY ze; GetZipItem(hz,i,&ze); return (ze.attr&FILE_ATTRIBUTE_DIRECTORY)!=0; }
bool GetCompressedFiles(std::string ZipName, std::vector<std::string>* pFileNames, std::vector<std::vector<char> >* data, std::string* pError) { #ifdef WIN32 HZIP hz = OpenZip(ZipName.c_str(),0); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} ZIPENTRY ze; if (GetZipItem(hz, -1, &ze) != ZR_OK) {if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} int NumFiles = ze.index; //set up returns for data... data->resize(NumFiles); for (int i=0; i<NumFiles; i++){ if (GetZipItem(hz,i,&ze) != ZR_OK) {if(pError) *pError += "Error loading ZIP file information. Aborting.\n"; return false;} int NumDesiredFiles = pFileNames->size(); for (int j=0; j<NumDesiredFiles; j++){ if ((*pFileNames)[j].compare(ze.name)==0){ //if this is one of the file's we're looking for int size = ze.unc_size; (*data)[j].resize(size+1); //or clear... if (UnzipItem(hz, i, &((*data)[j].front()), size) != ZR_OK) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[j][size] = '\0'; } } } if (CloseZip(hz) != ZR_OK) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #else //Mac/Linux Zip read code int err; struct zip * hz = zip_open(ZipName.c_str(), ZIP_CHECKCONS, &err); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} int NumFiles = zip_get_num_entries(hz,0); if (NumFiles < 0) { if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} //set up returns for data... data->resize(NumFiles); for (uint i=0; i<NumFiles; i++){ struct zip_file * zfile = zip_fopen_index(hz, i, 0); int NumDesiredFiles = pFileNames->size(); const char * entryname = zip_get_name(hz, i, 0); struct zip_stat stat; err = zip_stat_index(hz, i, 0, &stat); for (int j=0; j<NumDesiredFiles; j++){ if ((*pFileNames)[j].compare(entryname)==0){ //if this is one of the file's we're looking for int size = stat.size; (*data)[j].resize(size+1); //or clear... if (zip_fread(zfile, &((*data)[j].front()), size) != size) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[j][size] = '\0'; } } zip_fclose(zfile); } if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #endif }
int unziplib_c::getCount() { ZIPENTRY ze; GetZipItem(hz,-1,&ze); Count = ze.index; return Count; }
bool UncompressAllFiles(std::string ZipName, std::vector<std::string>* pFileNames, std::vector<std::vector<char> >* data, std::string* pError) { #ifdef WIN32 HZIP hz = OpenZip(ZipName.c_str(),0); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} ZIPENTRY ze; if (GetZipItem(hz, -1, &ze) != ZR_OK) {if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} int NumFiles = ze.index; //set up returns for the number of files... pFileNames->resize(NumFiles); data->resize(NumFiles); for (int i=0; i<NumFiles; i++){ if (GetZipItem(hz,i,&ze) != ZR_OK) {if(pError) *pError += "Error loading ZIP file information. Aborting.\n"; return false;} int size = ze.unc_size; (*data)[i].resize(size+1); if (UnzipItem(hz, i, &((*data)[i].front()), size) != ZR_OK) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[i][size] = '\0'; (*pFileNames)[i] = ze.name; } if (CloseZip(hz) != ZR_OK) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #else //Mac/Linux Zip read code int err; struct zip * hz = zip_open(ZipName.c_str(), ZIP_CHECKCONS, &err); if (!hz){if(pError) *pError += ("Unable to open ZIP archive. Aborting.\n"); return false;} int NumFiles = zip_get_num_entries(hz,0); if (NumFiles < 0) { if(pError) *pError += ("Unable to return information about ZIP archive. Aborting.\n"); return false;} //set up returns for the number of files... pFileNames->resize(NumFiles); data->resize(NumFiles); for (int i=0; i<NumFiles; i++){ struct zip_stat stat; err = zip_stat_index(hz, i, 0, &stat); int size = stat.size; (*data)[i].resize(size+1); struct zip_file * zfile = zip_fopen_index(hz, i, 0); if (zip_fread(zfile, &((*data)[i].front()), size) != size) {if(pError) *pError += "Could not unzip sub-file. Aborting.\n"; return false;} (*data)[i][size] = '\0'; (*pFileNames)[i] = zip_get_name(hz, i, 0); } if (zip_close(hz) != 0) {if(pError) *pError += "Error closing ZIP file.\n"; return false;} return true; #endif }
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine) { PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; CResource zipResource; wchar_t targetDir[MAX_PATH]; wchar_t logFile[MAX_PATH]; std::vector<CString> to_delete; ExpandEnvironmentStrings(L"%LocalAppData%\\SquirrelTemp", targetDir, _countof(targetDir)); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { goto failedExtract; } swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir); if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { goto failedExtract; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { goto failedExtract; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); SetUnzipBaseDir(zipFile, targetDir); // NB: This library is kind of a disaster ZRESULT zr; int index = 0; do { ZIPENTRY zentry; wchar_t targetFile[MAX_PATH]; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } // NB: UnzipItem won't overwrite data, we need to do it ourselves swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name); DeleteFile(targetFile); if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break; to_delete.push_back(CString(targetFile)); index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); // nfi if the zip extract actually worked, check for Update.exe wchar_t updateExePath[MAX_PATH]; swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe"); if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) { goto failedExtract; } // Run Update.exe si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) { lpCommandLine = L"--install ."; } wchar_t cmd[MAX_PATH]; swprintf_s(cmd, L"%s %s", updateExePath, lpCommandLine); if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) { goto failedExtract; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwExitCode; if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) { dwExitCode = (DWORD)-1; } if (dwExitCode != 0) { DisplayErrorMessage(CString( L"There was an error while installing the application. " L"Check the setup log for more information and contact the author."), logFile); } for (unsigned int i = 0; i < to_delete.size(); i++) { DeleteFile(to_delete[i]); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (int) dwExitCode; failedExtract: DisplayErrorMessage(CString(L"Failed to extract installer"), NULL); return (int) dwExitCode; }