struct CAddInfo
{
CAddInfo(){}
CAddInfo(const CString& szName, DWORD iSize, bool bDir = false)
:m_szName(szName), m_iSize(iSize), m_bDir(bDir){}
CString m_szName;
bool m_bDir;
DWORD m_iSize;
};
void main()
{
string strSrcFolder = "F://test_app//WriteXml";
string strTargetFoler = "F://test_app//TempZip";
int nCount = 100;
ZipFile(strSrcFolder, nCount, strTargetFoler);
}
bool ZipFile(const string& strSrcFolder, int iCount, const string& strTargetFoler)
{
string strSrcMap = "F://test_app//";
char cwd[_MAX_PATH];
getcwd(cwd,sizeof(cwd));
_chdir(strSrcMap.c_str());
string strTargetComp = "WriteXml";
CAddInfoList list;
AddFolder(strTargetComp.c_str(), list);
CAddInfoList list2;
int iCounter = 0;
try
{
POSITION pp = list.GetHeadPosition();
while (pp)
{
CAddInfo* padi = &list.GetNext(pp);
list2.AddTail(*padi);
if(!padi->m_bDir)
iCounter ++;
if(iCounter >= iCount)
{
DoZip(list2, strSrcMap, strTargetFoler);
iCounter = 0;
list2.RemoveAll();
}
}
if(iCounter > 0)
DoZip(list2, strSrcMap, strTargetFoler);
}
catch(...)
{
AfxMessageBox(_T("The system failed to zip file."), MB_ICONSTOP);
_chdir(cwd);
return false;
}
_chdir(cwd);
return true;
}
void AddFolder(CString szFolder, CAddInfoList& list)
{
szFolder.TrimRight(_T("//"));
CFileFind ff;
BOOL b = ff.FindFile(szFolder + _T("//*"));
CStringArray folders;
while (b)
{
b = ff.FindNextFile();
if (ff.IsDots())
continue;
if (ff.IsDirectory())
{
folders.Add(ff.GetFilePath());
}
else
{
CString szFile = ff.GetFilePath();
CFileStatus fs;
if (CFile::GetStatus(szFile, fs))
{
list.AddTail(CAddInfo(szFile, fs.m_size));
}
}
}
for (int i = 0; i < folders.GetSize(); i++)
{
list.AddTail(CAddInfo(folders[i], 0, true));
AddFolder(folders[i], list);
}
}
bool DoZip(CAddInfoList& list, const string& strSrcMap, const string& strTargetFolder)
{
static string strName = "1";
strName += "1";
CString szFolder = strTargetFolder.c_str();
szFolder.TrimRight(_T("//"));
string strTargetMap = szFolder;
strTargetMap += "//";
strTargetMap += strName + ".rar";
CZipArchive zipAr;
CFileStatus st;
if( CFile::GetStatus( strTargetMap.c_str(), st ) )
{
st.m_attribute = 0;
CFile::SetStatus( strTargetMap.c_str(), st );
}
try
{
zipAr.Open(strTargetMap.c_str(), CZipArchive::create);
}
catch(...)
{
AfxMessageBox(_T("The system failed to zip file."), MB_ICONSTOP);
return false;
}
try
{
POSITION pp = list.GetHeadPosition();
while (pp)
{
CAddInfo* padi = &list.GetNext(pp);
string strPrePath = strSrcMap;
string strFullPath = padi->m_szName;
string strFile = strFullPath.substr(strPrePath.size(), strFullPath.size());
if(strFile.empty())
continue;
zipAr.AddNewFile(strFile.c_str(), -1
, true
);
}
zipAr.Close();
}
catch(...)
{
AfxMessageBox("The system failed to zip file.",MB_ICONQUESTION);
zipAr.Close(true);
return false;
}
return true;
}