#include <iostream>
#include <Windows.h>
#include <string>
#include <time.h>
std::wstring GenerateBakDir(const std::wstring &srcDir)
{
std::wstring bakDir;
if (srcDir.empty())
{
return bakDir;
}
time_t curTime = time(0);
tm tim;
localtime_s(&tim, &curTime);
wchar_t format[32] = {0};
swprintf_s(format, 32, L"%d%02d%02d%02d%02d", tim.tm_year+1900, tim.tm_mon+1, tim.tm_mday, tim.tm_hour, tim.tm_min);
bakDir = srcDir;
bakDir += L"_";
bakDir += format;
return bakDir;
}
int CopyDir(const wchar_t *wSrcDir, const wchar_t *wDistDir)
{
int iCopyFileCount = 0;
if (!CreateDirectory(wDistDir, NULL))
{
if( GetLastError() == ERROR_PATH_NOT_FOUND )
{
return -1;
}
}
BOOL fFinished = FALSE;
wchar_t wSrcFile[MAX_PATH];
ZeroMemory(wSrcFile, sizeof(wSrcFile));
wcscpy_s(wSrcFile, MAX_PATH-1, wSrcDir);
wcscat_s(wSrcFile, L"\\*.*");
WIN32_FIND_DATA FileData;
HANDLE hSearch;
hSearch = FindFirstFile(wSrcFile, &FileData);
if (hSearch == INVALID_HANDLE_VALUE)
{
printf("FindFirstFile error, lasterror=%d\n", GetLastError());
return -1;
}
do
{
wcscpy_s(wSrcFile, MAX_PATH, wSrcDir);
wcscat_s(wSrcFile, MAX_PATH, L"\\");
wcscat_s(wSrcFile, MAX_PATH, FileData.cFileName);
wchar_t wDistFile[MAX_PATH];
ZeroMemory(wDistFile, sizeof(wDistFile));
wcscpy_s(wDistFile, MAX_PATH, wDistDir);
wcscat_s(wDistFile, MAX_PATH, L"\\");
wcscat_s(wDistFile, MAX_PATH, FileData.cFileName);
if (CopyFile(wSrcFile, wDistFile, FALSE))
{
iCopyFileCount++;
}
}while(FindNextFile(hSearch, &FileData));
FindClose(hSearch);
return iCopyFileCount;
}
BOOL WinRARCompress(const std::wstring &dir, unsigned long timeout)
{
SHELLEXECUTEINFOW info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.hwnd = NULL;
info.lpVerb = NULL;
info.lpFile = L"WinRAR.exe";
std::wstring workPath;
std::wstring compressDir;
size_t pos = dir.find_last_of(L"\\");
if (pos == std::string::npos)
{
pos = dir.find_last_of(L"/");
}
if (pos != std::string::npos)
{
workPath = dir.substr(0, pos);
compressDir = dir.substr(pos + 1, dir.length() - pos);
}
else
{
return FALSE;
}
if (workPath.empty() || compressDir.empty())
{
return FALSE;
}
wchar_t wParameter[_MAX_PATH];
ZeroMemory(wParameter, sizeof(wParameter));
swprintf_s(wParameter, _MAX_PATH, L"a %s.rar %s", compressDir.c_str(), compressDir.c_str());
info.lpParameters = wParameter;
info.lpDirectory = workPath.c_str();
info.nShow = SW_HIDE;
info.hInstApp = NULL;
BOOL bret = ShellExecuteEx(&info);
if (bret)
{
if (WAIT_OBJECT_0 == WaitForSingleObject(info.hProcess, timeout))
{
bret = TRUE;
}
}
else
{
bret = FALSE;
}
if (!bret)
{
DWORD lasterror = GetLastError();
printf("ShellExecuteEx error, lasterror:%d\n", lasterror);
}
return bret;
}
使用winrar打包文件
最新推荐文章于 2024-09-13 15:48:04 发布