Example #1
0
BOOL CMetadata::Save()
{
	if(!OpenZip(OPEN_SAVE))
		return 0;

	CMetaObject *p;
	POSITION pos;
	CString csKey;


	//сначала обрабатываем удаляемые элементы
	for( pos = ListObjects.GetStartPosition(); pos != NULL; )
	{
		ListObjects.GetNextAssoc( pos, csKey, (void*&)p );
		if(p)
			if(p->IsDeleted)
				p->Save
				(m_zip,"");
	}

	for( pos = ListObjects.GetStartPosition(); pos != NULL; )
	{
		ListObjects.GetNextAssoc( pos, csKey, (void*&)p );
		if(p)
		if(!p->IsDeleted)
		if(p->pTree)
		if(p->nTempID)
			p->Save(m_zip,p->pTree->GetPath(p->nTempID));
	}
	OpenZip(CLOSE_FILE); //временное закрытие
	return TRUE;
}
Example #2
0
CUnzipper::CUnzipper(LPCTSTR szFileName) : m_uzFile(0),
	mCallbackFn(DefUnzipCallback), muUncompressedSize(0)
{
	m_szOutputFolder[0] = 0;

	OpenZip(szFileName);
}
//
// Locks the currently loaded resource file and unzips it.
//  
// This function should only be used when the resource file
// is a zip file and you want to extract one or more files within it.
//
void DLLResourceManager::OpenMainResourceZipFile()
{
	void *zipbuf=LockResource(hglob);
	unsigned int ziplen=SizeofResource(handleToDll,hRsrc);
	hz = OpenZip(zipbuf, ziplen, 0);  
	SetUnzipBaseDir(hz,_T("\\"));
}
Example #4
0
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;
}
Example #5
0
void CPropertiesFiles::OnBnClickedPropPreview()
{
	// TODO: 在此加入控制項告知處理常式程式碼
	CListBox* listBox=(CListBox*)this->GetDlgItem(IDC_PROP_FILELIST);
	int curSel=listBox->GetCurSel();

	if (curSel>=0) {
		LPTSTR pszFile=(LPTSTR)malloc(listBox->GetTextLen(curSel)+1);
		HZIP hZip;
		ZIPENTRY ze;
		CARMDlg* dlg=(CARMDlg*)this->GetParentOwner()->GetParent();
		arfile* arFile=(arfile*)dlg->m_lstFiles.GetItemDataPtr(dlg->m_lstFiles.GetCurSel());

		listBox->GetText(curSel,pszFile);
		hZip=OpenZip(arFile->fileName,0,ZIP_FILENAME);
		if (hZip) {
			int nIndex;
			if (FindZipItem(hZip,pszFile,TRUE,&nIndex,&ze)!=ZR_ARGS) {
				LPBYTE pszContent=(LPBYTE)malloc(ze.unc_size);
				UnzipItem(hZip,nIndex,pszContent,ze.unc_size,ZIP_MEMORY);
				bitmapInfo=&ze;

				DialogBoxParam(theApp.m_hInstance,MAKEINTRESOURCE(IDD_PREVIEW),this->GetSafeHwnd(),(DLGPROC)CPropertiesFiles::previewWndProc,(LPARAM)pszContent);
				free(pszContent);
			}

			CloseZip(hZip);
		}

		free(pszFile);
	}
}
Example #6
0
CZipper::CZipper(LPCTSTR szFilePath, LPCTSTR szRootFolder, bool bAppend) : m_uzFile(0)
{
	CloseZip();

	if (szFilePath)
		OpenZip(szFilePath, szRootFolder, bAppend);
}
Example #7
0
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);
}
Example #8
0
int FbUpdateItem::Execute()
{
	FbLogWarning(_("Update collection"), m_url);
	bool ok = FbInternetBook::Download(m_url, m_filename);
	if (ok) ok = OpenZip();
	if (ok) return DoUpdate();
	return 0;
}
Example #9
0
int CMetadata::DeleteData(CString csPath)
{
	if(!OpenZip(OPEN_SAVE))
		return 0;

	if(m_zip.FindFile(csPath))
		return ::DeleteFile(m_zip,csPath);
	else
		return ::DeleteFolder(m_zip,csPath);
}
Example #10
0
//получение метаобъекта (если такой метаобъект еще не загружен из файла, то он загружается)
CMetaObject *CMetadata::GetMetaObject2(CString csFileName,CString csObjName,int bReadOnly) 
{
	if(!OpenZip(OPEN_LOAD))
		return 0;


	if(afxAppRunMode==ENTERPRISE_MODE || bIsLibrary)
		bReadOnly=1;

	CMetaObject *pObject=(CMetaObject *)ListObjects[mUpper(csFileName)];
	if(pObject)
	{ 
		if(!csObjName.IsEmpty()&&pObject->csOldName!=pObject->csName)
		{
			//было изменено имя - переписываем указатель
			ListObjects[mUpper(pObject->csName)]=pObject;
			pObject=0;
		}
		else
		{
			if(pObject->IsDeleted)
			{//объект был удален - значит больше его не грузим
				pObject=new CMetaObject();
				ListObjects[mUpper(csFileName)]=pObject;
			}
			if(!bReadOnly)//если объекта берется для изменения, то разрешаем его последующую запись
				pObject->bCanSave=1;
			return pObject;
		}
	}

	if(bReadOnly)//проверяем физическое наличие в файле метаданных
	{
		int n1=m_zip.FindFile(csFileName);
		if(n1<0)
			n1=m_zip.FindFile(csFileName+".inf");
		if(n1<0)
			n1=m_zip.FindFile(csFileName+".2c");
		if(n1<0)
		{
			return 0;
		}
	}

	pObject=new CMetaObject();
	if(bReadOnly)//объект еще не загружался + режим взятия только для чтения - помечаем его как незаписываемый (для уменьшения трафика)
		pObject->bCanSave=0;
	ListObjects[mUpper(csFileName)]=pObject;
	pObject->Load(m_zip,csFileName,csObjName);

//	OpenZip(CLOSE_FILE); //временное закрытие

	return pObject;
}
Example #11
0
void ZipByteReader::Register(size_t seqId, const std::string& path)
{
    auto zipFile = m_zips.pop_or_create([this]() { return OpenZip(); });
    zip_stat_t stat;
    zip_stat_init(&stat);
    int err = zip_stat(zipFile.get(), path.c_str(), 0, &stat);
    if (ZIP_ER_OK != err)
        RuntimeError("Failed to get file info of %s, zip library error: %s", path.c_str(), GetZipError(err).c_str());
    m_seqIdToIndex[seqId] = std::make_pair(stat.index, stat.size);
    m_zips.push(std::move(zipFile));
}
Example #12
0
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;
	}
}
Example #13
0
void CMetadata::AllFind(CString csFind,int nCase,int nWorld) 
{
	if(csFind.IsEmpty())
		return;
	csFind.TrimRight();
	csFind.TrimLeft();
	if(!nCase)
		csFind.MakeUpper();

	int nCount=0;
	if(OpenZip(OPEN_LOAD))
	{
		int nEntries=m_zip.GetNoEntries();
		CZipFileHeader fhInfo;
		for (WORD i = 0; i < nEntries; i++)
		{
			if(EscapePress())
			{
				Message("Поиск прерван пользователем");
				return;
			}
			if(!m_zip.IsFileDirectory(i))
			{
				m_zip.GetFileInfo(fhInfo, i);
				CString csFileName=fhInfo.GetFileName();

				CMetaObject *pObj=GetMetaObject(csFileName,"",1);
				if(pObj)
				{
					CString csFile=pObj->csFile;
					if(!nCase)
						csFile.MakeUpper();

					int nPos=csFile.Find(csFind); 
					if(nPos>=0)
					{
						CString csText=FindErrorCodeLine(pObj->csFile,nPos,3);


						CString StrMessage;
						StrMessage.Format("%s %s",csFileName,csText);
						Message(StrMessage);
						nCount++;
						nPos=csFile.Find(csFind,nPos+1);
					}
				}
			}
		}
	}
	CString Str;
	Str.Format("Всего найдено %d",nCount);
	Message(Str);
}
Example #14
0
BOOL WINAPI duWindowManager::OpenSkinZip(LPCTSTR lpszZipFile, LPCSTR lpszZipPassword)
{
	if (lpszZipFile == NULL || *lpszZipFile == 0 || !::PathFileExists(lpszZipFile))
		return FALSE;
	
	m_fZip = TRUE;
	m_hZip = OpenZip(lpszZipFile, lpszZipPassword);
	if (m_hZip == NULL)
		return FALSE;
	
	return OpenSkin(lpszZipFile);
}
Example #15
0
BOOL WINAPI duWindowManager::OpenSkinMemory(BYTE *pData, int nSize)
{
	if (pData == NULL || nSize <= 0)
		return FALSE;
	
	m_fZip = TRUE;
	m_hZip = OpenZip(pData, nSize, NULL);
	if (m_hZip == NULL)
		return FALSE;
	
	return OpenSkin(_T("Memory\\"));
}
Example #16
0
cv::Mat ZipByteReader::Read(size_t seqId, const std::string& path, bool grayscale)
{
    // Find index of the file in .zip file.
    auto r = m_seqIdToIndex.find(seqId);
    if (r == m_seqIdToIndex.end())
        RuntimeError("Could not find file %s in the zip file, sequence id = %lu", path.c_str(), (long)seqId);

    zip_uint64_t index = std::get<0>((*r).second);
    zip_uint64_t size = std::get<1>((*r).second);

    auto contents = m_workspace.pop_or_create([size]() { return vector<unsigned char>(size); });
    if (contents.size() < size)
        contents.resize(size);
    auto zipFile = m_zips.pop_or_create([this]() { return OpenZip(); });
    {
        std::unique_ptr<zip_file_t, void(*)(zip_file_t*)> file(
            zip_fopen_index(zipFile.get(), index, 0),
            [](zip_file_t* f)
            {
                assert(f != nullptr);
                int err = zip_fclose(f);
                assert(ZIP_ER_OK == err);
#ifdef NDEBUG
                UNUSED(err);
#endif
            });
        assert(nullptr != file);
        if (nullptr == file)
        {
            RuntimeError("Could not open file %s in the zip file, sequence id = %lu, zip library error: %s",
                         path.c_str(), (long)seqId, GetZipError(zip_error_code_zip(zip_get_error(zipFile.get()))).c_str());
        }
        assert(contents.size() >= size);
        zip_uint64_t bytesRead = zip_fread(file.get(), contents.data(), size);
        assert(bytesRead == size);
        if (bytesRead != size)
        {
            RuntimeError("Bytes read %lu != expected %lu while reading file %s",
                         (long)bytesRead, (long)size, path.c_str());
        }
    }
    m_zips.push(std::move(zipFile));

    cv::Mat img; 
    if (grayscale)
        img = cv::imdecode(cv::Mat(1, (int)size, CV_8UC1, contents.data()), cv::IMREAD_GRAYSCALE);
    else
        img = cv::imdecode(cv::Mat(1, (int)size, CV_8UC1, contents.data()), cv::IMREAD_COLOR);
    assert(nullptr != img.data);
    m_workspace.push(std::move(contents));
    return img;
}
Example #17
0
HZIP OpticPack::open(const std::string& fileName) {
    char buff[1024];
    GetCurrentDirectory(1024, buff);

    std::string fullPath = buff + std::string("\\") + fileName;

    HZIP handle = OpenZip((void*)fullPath.c_str(), 0, ZIP_FILENAME);

    if(handle == NULL) {
        std::cout << "Null zip" << std::endl;
        throw OpticPackException("fail");
    }

    return handle;
}
Example #18
0
BOOL CUnzipper::Unzip(LPCTSTR szFileName, LPCTSTR szFolder, BOOL bIgnoreFilePath)
{
	CloseZip();

	if (!OpenZip(szFileName))
		return FALSE;
	if (szFolder == NULL)
		szFolder = m_szOutputFolder;

	BOOL bRet = UnzipTo(szFolder, bIgnoreFilePath);

	CloseZip();

	return bRet;
}
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 "";
}
Example #20
0
int CUpdateThread::UnzipPackage(wchar_t* pPackageName)
{
	if( pPackageName == NULL)
		return -1;

	// 启动线程,进行更新
	HZIP hz = OpenZip((void*)pPackageName, 0, 2);

	unsigned int nZipItemNum;
	ZRESULT zResult = GetZipItemNum(hz, &nZipItemNum);
	if( zResult != ZR_OK)
		return -1;

	size_t i=0;
	for( ; i<nZipItemNum; i++)
	{
		ZIPENTRY ze; 
		zResult = GetZipItemA(hz, i, &ze);
		if( zResult != ZR_OK)
			continue;

		USES_CONVERSION;
		wchar_t* pName = wcsdup(A2W(ze.name));

		wchar_t szName[MAX_PATH];
		memset(szName, 0x0, MAX_PATH);
		swprintf(szName, L"%s%s", MiscHelper::GetUnpackagePath(),pName);
		zResult = UnzipItem(hz, i, (void*)szName, wcslen(szName),ZIP_FILENAME);

		// 解压失败
		if( zResult != ZR_OK)
			break;

		FileHelper::ModifyFileAttribute(szName, 0, FILE_ATTRIBUTE_READONLY);
	}
	CloseZip(hz);

	// 更新失败
	if( i < nZipItemNum)
	{
		::MessageBox(NULL, L"安装包解压失败,无法正确进行更新", L"更新提示", MB_OK);
		return -1;
	}

	return 0;
}
Example #21
0
// 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;
}
Example #22
0
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;
}
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;
}
Example #24
0
void test_unzip()
{
    wstring sFilePath;
    sFilePath = L"c:\\1.zip";

    HZIP hz = OpenZip((void *)sFilePath.c_str(), 0, 2);
    if( hz == NULL )
    {
        cout<<"Error opening zip file"<<endl;
        return;
    }
    ZIPENTRY ze; 
    int i; 
    if( FindZipItem(hz, L"1.txt", true, &i, &ze) != 0 )
    {
        cout<<"Could not find ziped file"<<endl;
        return;
    }
    DWORD dwSize = ze.unc_size;
    if( dwSize == 0 ) 
    {
        cout<<"File is empty";
        return;
    }
    if ( dwSize > 4096*1024 ) 
    {
        cout<<"File too large";
        return;
    }
    BYTE* pByte = new BYTE[ dwSize + 1 ];
    ZeroMemory(pByte, dwSize + 1);
    int res = UnzipItem(hz, i, pByte, dwSize, 3);
    if( res != 0x00000000 && res != 0x00000600)
    {
        delete[] pByte;
        CloseZip(hz);
        cout<<"Could not unzip file";
        return;
    }
    CloseZip(hz);
    cout<<pByte<<endl;
    delete[] pByte;
}
Example #25
0
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;
}
Example #26
0
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;
}
Example #28
0
void ZipByteReader::Register(const std::map<std::string, size_t>& sequences)
{
    auto zipFile = m_zips.pop_or_create([this]() { return OpenZip(); });
    zip_stat_t stat;
    zip_stat_init(&stat);

    size_t numberOfEntries = 0;
    size_t numEntries = zip_get_num_entries(zipFile.get(), 0);
    for (size_t i = 0; i < numEntries; ++i) {
        int err = zip_stat_index(zipFile.get(), i, 0, &stat);
        if (ZIP_ER_OK != err)
            RuntimeError("Failed to get file info for index %d, zip library error: %s", (int)i, GetZipError(err).c_str());

        auto sequenceId = sequences.find(std::string(stat.name));
        if (sequenceId == sequences.end())
        {
            continue;
        }
        else
        {
            m_seqIdToIndex[sequenceId->second] = std::make_pair(stat.index, stat.size);
            numberOfEntries++;
        }
    }
    m_zips.push(std::move(zipFile));

    if (numberOfEntries != sequences.size())
    {
        // Not all sequences have been found. Let's print them out and throw.
        for (const auto& s : sequences)
        {
            auto index = m_seqIdToIndex.find(s.second);
            if (index == m_seqIdToIndex.end())
            {
                fprintf(stderr, "Sequence %s is not found in container %s.\n", s.first.c_str(), m_zipPath.c_str());
            }
        }

        RuntimeError("Cannot retrieve image data for some sequences. For more detail, please see the log file.");
    }
}
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;
}
Example #30
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);
	}