⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ziparchive.cpp

📁 编写的ZIP的小程序
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// ZipArchive.cpp: implementation of the CZipArchive class.
//
////////////////////////////////////////////////////////////////////////////////
//  Copyright (C) 2000 Tadeusz Dracz.
//  For conditions of distribution and use, see copyright notice in ZipArchive.h
////////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ZipArchive.h"
#include <direct.h>
#include <stdlib.h> // for qsort


#ifndef DEF_MEM_LEVEL
#if MAX_MEM_LEVEL >= 8
#  define DEF_MEM_LEVEL 8
#else
#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
#endif
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
char CZipArchive::m_gszCopyright[] = {"Zip archive creation and modification Copyright 2000 Tadeusz Dracz"};
CZipArchive::CZipArchive()
{
	m_bSlashChange = m_bDetectZlibMemoryLeaks = m_bOemCompatible = true;
	m_centralDir.m_pStorage= &m_storage;
	m_info.m_stream.zalloc = (alloc_func)myalloc;
	m_info.m_stream.zfree = (free_func)myfree;
}


CZipArchive::~CZipArchive()
{
	// 	Close(); // cannot be here: if an exception is thrown strange things can happen
	
	if (m_list.GetCount())
	{
		// if some memory hasn't been freed due to an error in zlib, so free it now
		POSITION pos = m_list.GetHeadPosition();
		while (pos)
			delete[] m_list.GetNext(pos);
	}
}

void CZipArchive::Open(LPCTSTR szPathName, int iMode, int iVolumeSize)
{
	if (!IsClosed())
	{
		TRACE("ZipArchive already opened.\n");
		return;
	}
	m_iFileOpened = nothing;
	m_storage.Open(szPathName, iMode, iVolumeSize);
	m_centralDir.Init();
	if ((iMode == open) ||(iMode == openReadOnly))
		m_centralDir.Read();
}

bool CZipArchive::IsClosed(bool bArchive)
{
	return  bArchive ?(m_storage.GetCurrentDisk() == -1):(m_storage.m_file.m_hFile == CFile::hFileNull);
}


void CZipArchive::ThrowError(int err)
{
	AfxThrowZipException(err, IsClosed() ? "" : m_storage.m_file.GetFilePath());
}

bool CZipArchive::DeleteFile(WORD uIndex)
{
	if (m_storage.IsSpanMode())
	{
		TRACE("You cannot delete files from the disk spannig archive.\n");
		return false;
	}
	
	if (m_iFileOpened)
	{
		TRACE("You cannot delete files if there is a file opened.\n");
		return false;
	}
	
	if (!m_centralDir.IsValidIndex(uIndex))
		return false;
	
	m_info.Init();
	m_centralDir.RemoveFromDisk();
	DeleteInternal(uIndex);
	m_info.m_pBuffer.Release();
	return true;
}

int CZipArchive::GetNoEntries()
{
	return m_centralDir.m_headers.GetSize();
}


bool CZipArchive::GetFileInfo(CFileHeader & fhInfo, WORD uIndex)
{
	if (IsClosed())
	{
		TRACE("ZipArchive is closed.\n");
		return false;
	}
	
	if (!m_centralDir.IsValidIndex(uIndex))
		return false;
	
	fhInfo = *(m_centralDir.m_headers[uIndex]);
	if (m_bOemCompatible)
		fhInfo.m_szFileName.OemToAnsi();
	if (m_bSlashChange)
		fhInfo.m_szFileName.Replace('/', '\\');
	return true;
}

int CZipArchive::FindFile(CString szFileName, bool bCaseSensitive)
{
	if (IsClosed())
	{
		TRACE("ZipArchive is closed.\n");
		return (int)-1;
	}
	
	for (WORD i = 0; i < GetNoEntries(); i++)
	{
		CFileHeader fh;
		GetFileInfo(fh, i);
		CString temp = fh.m_szFileName;
		if ((bCaseSensitive ? temp.Collate(szFileName) : temp.CollateNoCase(szFileName)) == 0)
			return (int)i;
	}
	return (int) - 1;
}

bool CZipArchive::OpenFile(WORD uIndex)
{
	if (!m_centralDir.IsValidIndex(uIndex))
		return false;
	
	if (m_storage.IsSpanMode() == 1)
	{
		TRACE("You cannot extract from the span in creation.\n");
		return false;
	}
	
	
	if (m_iFileOpened)
	{
		TRACE("A file already opened.\n");
		return false;
	}
	
	m_info.Init();
	m_centralDir.OpenFile(uIndex);
	
	WORD uMethod = CurrentFile()->m_uMethod;
	if ((uMethod != 0) &&(uMethod != Z_DEFLATED))
		ThrowError(ZIP_BADZIPFILE);
	
	if (uMethod == Z_DEFLATED)
	{
		m_info.m_stream.opaque =  m_bDetectZlibMemoryLeaks ? &m_list : 0;
		int err = inflateInit2(&m_info.m_stream, -MAX_WBITS);
		//			* windowBits is passed < 0 to tell that there is no zlib header.
		//          * Note that in this case inflate *requires* an extra "dummy" byte
		//          * after the compressed stream in order to complete decompression and
		//          * return Z_STREAM_END. 
		CheckForError(err);
	}
	m_info.m_uComprLeft = CurrentFile()->m_uComprSize;
	m_info.m_uUncomprLeft = CurrentFile()->m_uUncomprSize;
	m_info.m_uCrc32 = 0;
	m_info.m_stream.total_out = 0;
	m_info.m_stream.avail_in = 0;
	
	m_iFileOpened = extract;
	return true;
}


int CZipArchive::GetLocalExtraField(char *pBuf, int iSize)
{
	if (IsClosed())
	{
		TRACE("ZipArchive is closed.\n");
		return false;
	}
	
	if (m_iFileOpened != extract)
	{
		TRACE("A file must be opened to get the local extra field.\n");
		return -1;
	}
	
	int size = m_centralDir.m_pLocalExtraField.GetSize();
	if (!pBuf|| !size)
		return size;
	
	if (iSize < size)
		size = iSize;
	
	memcpy(pBuf, m_centralDir.m_pLocalExtraField, size);
	return size;
}

void* CZipArchive::myalloc(void* opaque, UINT items, UINT size)
{
	void* p = new char[size * items];
	if (opaque)
	{
		CPtrList* list  = (CPtrList*) opaque;
		list->AddTail(p);
	}
	return p;
}

void CZipArchive::myfree(void* opaque, void* address)
{
	if (opaque)
	{
		CPtrList* list  = (CPtrList*) opaque;
		POSITION pos = list->Find(address);
		if (pos)
			list->RemoveAt(pos);
	}
	delete[] address;
}

void CZipArchive::CheckForError(int iErr)
{
	if ((iErr == Z_OK) ||(iErr == Z_NEED_DICT))
		return;
	
	ThrowError(iErr);
}

CFileHeader* CZipArchive::CurrentFile()
{
	ASSERT(m_centralDir.m_pOpenedFile);
	return m_centralDir.m_pOpenedFile;
}

DWORD CZipArchive::ReadFile(void *pBuf, DWORD iSize)
{
	if (m_iFileOpened != extract)
	{
		TRACE("Current file must be opened.\n");
		return 0;
	}
	
	if (!pBuf || !iSize)
		return 0;
	
	m_info.m_stream.next_out = (Bytef*)pBuf;
	m_info.m_stream.avail_out = iSize > m_info.m_uUncomprLeft 
		? m_info.m_uUncomprLeft : iSize;
	
	
	DWORD iRead = 0;
	
	while (m_info.m_stream.avail_out > 0)
	{
		if ((m_info.m_stream.avail_in == 0) &&
			(m_info.m_uComprLeft > 0))
		{
			DWORD uToRead = m_info.m_pBuffer.GetSize();
			if (m_info.m_uComprLeft < uToRead)
				uToRead = m_info.m_uComprLeft;
			
			if (uToRead == 0)
				return 0;
			
			m_storage.Read(m_info.m_pBuffer, uToRead, false);
			m_info.m_uComprLeft -= uToRead;
			
			m_info.m_stream.next_in = (unsigned char*)(char*)m_info.m_pBuffer;
			m_info.m_stream.avail_in = uToRead;
		}
		
		if (CurrentFile()->m_uMethod == 0)
		{
			DWORD uToCopy = m_info.m_stream.avail_out < m_info.m_stream.avail_in 
				? m_info.m_stream.avail_out : m_info.m_stream.avail_in;
			
			memcpy(m_info.m_stream.next_out, m_info.m_stream.next_in, uToCopy);
			
			m_info.m_uCrc32 = crc32(m_info.m_uCrc32, m_info.m_stream.next_out, uToCopy);
			
			m_info.m_uUncomprLeft -= uToCopy;
			m_info.m_stream.avail_in -= uToCopy;
			m_info.m_stream.avail_out -= uToCopy;
			m_info.m_stream.next_out += uToCopy;
			m_info.m_stream.next_in += uToCopy;
            m_info.m_stream.total_out += uToCopy;
			iRead += uToCopy;
		}
		else
		{
			DWORD uTotal = m_info.m_stream.total_out;
			Bytef* pOldBuf =  m_info.m_stream.next_out;
			int err = inflate(&m_info.m_stream, Z_SYNC_FLUSH);
			DWORD uToCopy = m_info.m_stream.total_out - uTotal;
			
			m_info.m_uCrc32 = crc32(m_info.m_uCrc32, pOldBuf, uToCopy);
			
			m_info.m_uUncomprLeft -= uToCopy;
			iRead += uToCopy;
            
			if (err == Z_STREAM_END)
				return iRead;
			
			CheckForError(err);
		}
	}
	
	return iRead;
}

void CZipArchive::Close(bool bAfterException)
{
	if (IsClosed())
	{
		TRACE("ZipArchive is already closed.\n");
		return;
	}
	
	if (!bAfterException)
	{
		if (m_iFileOpened == extract)
			CloseFile(NULL);
		
		if (m_iFileOpened == compress)
			CloseNewFile();
		
		m_centralDir.Write();
	}
	m_centralDir.Clear();
	
	m_storage.Close(bAfterException);
}

void CZipArchive::SetSpanCallback(CHANGEDISKFUNC pFunc, void* pData)
{
	m_storage.m_pChangeDiskFunc = pFunc;
	m_storage.m_pCallbackData = pData;
}

void CZipArchive::SetAdvanced(int iWriteBuffer, int iExtractBuffer, int iSearchBuffer)
{
	if (!IsClosed())
	{
		TRACE("Set this options before opening the archive.\n");
		return;
	}
	
	m_storage.m_iWriteBufferSize = iWriteBuffer < 1024 ? 1024 : iWriteBuffer;
	m_centralDir.m_iBufferSize = iSearchBuffer < 1024 ? 1024 : iSearchBuffer;
	m_info.m_iBufferSize = iExtractBuffer < 1024 ? 1024 : iExtractBuffer;
}

bool CZipArchive::CloseFile(CFile &file)
{
	CString temp = file.GetFilePath();
	file.Close();
	return CloseFile(temp);
}

bool CZipArchive::CloseFile(LPCTSTR lpszFilePath)
{
	if (m_iFileOpened != extract)
	{
		TRACE("No file opened.\n");
		return false;
	}
	
	if (m_info.m_uUncomprLeft == 0)
	{
		if (m_info.m_uCrc32 != CurrentFile()->m_uCrc32)
			ThrowError(ZIP_BADCRC);
	}
	
	
	if (CurrentFile()->m_uMethod == Z_DEFLATED)
		inflateEnd(&m_info.m_stream);
	
	
	bool bRet = true;
	if (lpszFilePath)
	{
		try
		{
			CFileStatus fs;
			fs.m_ctime = fs.m_atime = CTime::GetCurrentTime();
			fs.m_attribute = 0;
			fs.m_mtime = CurrentFile()->GetTime();
			CFile::SetStatus(lpszFilePath, fs);
			bRet = SetFileAttributes(lpszFilePath, CurrentFile()->m_uExternalAttr) != 0;
		}
		catch (CException* e)
		{
			e->Delete();
			return false;
		}
	}
	m_centralDir.CloseFile();
	m_iFileOpened = nothing;
	m_info.m_pBuffer.Release();
	return bRet;
}

bool CZipArchive::OpenNewFile(CFileHeader & header, int iLevel, const char* lpszFilePath)
{
	if (IsClosed())
	{
		TRACE("ZipArchive is closed.\n");
		return false;
	}
	
	if (m_iFileOpened)
	{
		TRACE("A file already opened.\n");
		return false;
	}
	
	if (m_storage.IsSpanMode() == -1)
	{
		TRACE("You cannot add the files to the existing disk spannig archive.\n");
		return false;
	}
	
	if (GetNoEntries() ==(WORD)USHRT_MAX)
	{
		TRACE("Maximum file count inside archive reached.\n");
		return false;
	}
	
	bool bRet = true;
	if (lpszFilePath)
	{
		CFileStatus fs;
		if (!CFile::GetStatus(lpszFilePath, fs))
			bRet = false;
		else
		{
			header.SetTime(fs.m_mtime);
			header.m_uExternalAttr = ::GetFileAttributes(lpszFilePath); // mfc bug: m_attribute is 1-byte
			if (header.m_uExternalAttr == -1)
			{
				header.m_uExternalAttr = FILE_ATTRIBUTE_ARCHIVE;
				bRet = false;
			}
		}
	}
	m_info.Init();
	
	m_centralDir.AddNewFile(header);
	CString* pszFileName = &(CurrentFile()->m_szFileName);
	if (m_bSlashChange)
		pszFileName->Replace('\\', '/');
	if (m_bOemCompatible)
		pszFileName->AnsiToOem();

	if (pszFileName->IsEmpty())
		pszFileName->Format("file%i", GetNoEntries());	

	if (!CurrentFile()->PrepareData(iLevel, m_storage.IsSpanMode() == 1))
		ThrowError(ZIP_TOOLONGFILENAME);
	CurrentFile()->WriteLocal(m_storage);
	
	
	m_info.m_uComprLeft = 0;
    m_info.m_stream.avail_in = (uInt)0;
    m_info.m_stream.avail_out = (uInt)m_info.m_pBuffer.GetSize();
    m_info.m_stream.next_out = (unsigned char*)(char*)m_info.m_pBuffer;
    m_info.m_stream.total_in = 0;
    m_info.m_stream.total_out = 0;
	
	if (IsDirectory(CurrentFile()->m_uExternalAttr) &&(CurrentFile()->m_uMethod != 0))
		CurrentFile()->m_uMethod = 0;
	
	if (CurrentFile()->m_uMethod == Z_DEFLATED)
    {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -