PublicFunction.cpp
上传用户:oadesign
上传日期:2013-12-25
资源大小:265k
文件大小:36k
- // PublicFunction.cpp: implementation of the CPublicFunction class.
- //
- //////////////////////////////////////////////////////////////////////
- #include "stdafx.h"
- #include "NetDownMTR.h"
- #include "PublicFunction.h"
- #include <Afxmt.h>
- #include <io.h>
- #include <direct.h>
- // for function StrTrim()
- #include "Shlwapi.h"
- #pragma comment ( lib, "Shlwapi.lib" )
- #ifdef _DEBUG
- #undef THIS_FILE
- static char THIS_FILE[]=__FILE__;
- #define new DEBUG_NEW
- #endif
- const char f_seps[] = ";";
- void DeleteStrAry(CStringArray **ppStrAry)
- {
- if ( ppStrAry && (*ppStrAry) )
- {
- (*ppStrAry)->RemoveAll();
- (*ppStrAry)->FreeExtra();
- delete (*ppStrAry);
- (*ppStrAry) = NULL;
- }
- }
- int PartStringAndAddToStrAry ( char *pStr, CStringArray &StrAry, char *seps/*="trn"*/ )
- {
- StrAry.RemoveAll();
- char *token;
- token = strtok( pStr, seps );
- while( token != NULL )
- {
- /* While there are tokens in "string" */
- StrAry.Add ( token );
- /* Get next token: */
- token = strtok( NULL, seps );
- }
- return StrAry.GetSize();
- }
- int PartStringAndAddToStrAry ( char *pStr, CStringArray &StrAry, char nPartFlag )
- {
- char *pStart = pStr;
- char *pFind = NULL;
- char szTempBuf[10240] = {0};
- LPCTSTR pszTrimChars = "rnt";
- while ( pFind = strchr ( pStart, nPartFlag ) )
- {
- int nLen = pFind - pStart;
- if ( nLen > 0 )
- {
- if ( nLen > sizeof(szTempBuf)-2 )
- nLen = sizeof(szTempBuf)-2;
- memcpy ( szTempBuf, pStart, nLen );
- szTempBuf [ nLen ] = ' ';
- StrTrim ( szTempBuf, pszTrimChars );
- StrAry.Add ( szTempBuf );
- }
- else
- {
- StrAry.Add ( "" );
- }
- pStart = pFind + 1;
- }
- if ( (int)( pStart - pStr ) < (int)strlen ( pStr ) )
- StrAry.Add ( pStart );
- return StrAry.GetSize();
- }
- int PartStringAndAddToStrAry ( LPCTSTR lpszStr, CStringArray &StrAry, char nFirstFlag, char nSecondFlag )
- {
- StrAry.RemoveAll();
- int nStartPos = 0, nEndPos = 0;
- CString csBigString = GET_SAFE_STRING ( lpszStr );
- BOOL bSentence = FALSE;
- for ( ;; )
- {
- char cFindChar = ( bSentence ? nSecondFlag : nFirstFlag );
- int nFindPos = csBigString.Find ( cFindChar, nEndPos );
- if ( nFindPos < 0 )
- {
- if ( bSentence )
- {
- CString csTemp = csBigString.Mid ( nStartPos+1 );
- if ( csTemp.GetLength() > 0 )
- StrAry.Add ( csTemp );
- }
- break;
- }
- if ( !bSentence )
- {
- nStartPos = nFindPos;
- bSentence = TRUE;
- }
- else
- {
- nEndPos = nFindPos;
- CString csTemp = csBigString.Mid ( nStartPos+1, nEndPos-nStartPos-1 );
- StrAry.Add ( csTemp );
- bSentence = FALSE;
- }
- nEndPos = nFindPos + 1;
- }
- return StrAry.GetSize();
- }
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- CHwDir::CHwDir(
- LPCTSTR lpszBasePathOrFile,
- BOOL bSerachSubDir/* = TRUE*/, // 搜索子目录
- BOOL bAbsolutePath /*=TRUE*/, // 是绝对路径
- CHwDir **ppHwDir/*=NULL*/ // 将这个类的指针传出去给调用者
- )
- {
- m_bCancel = FALSE;
- if ( ppHwDir ) *ppHwDir = this;
- m_pStrAryResFile = new CStringArray;
- if ( !m_pStrAryResFile ) return;
- m_pStrArySubDirectory_Private = new CStringArray;
- if ( !m_pStrArySubDirectory_Private ) return;
- m_pStrArySubDirectory = new CStringArray;
- if ( !m_pStrArySubDirectory ) return;
- //初始化变量
- char buf[MAX_PATH];
- m_bSerachSubDir = bSerachSubDir;
- m_bAbsolutePath = bAbsolutePath;
- m_pStrAryResFile->FreeExtra();
- m_pStrArySubDirectory_Private->FreeExtra();
- m_pStrArySubDirectory->FreeExtra();
- m_dwRelativePathStartPos = 0;
- ZeroMemory(m_szBasePathFile,sizeof(m_szBasePathFile));
- int iLen = 0;
- char *p = NULL;
- ZeroMemory(m_strFilter,sizeof(m_strFilter));
- m_AmountBytes = 0;
- iLen = hwSnprintf((char*)m_szBasePathFile,sizeof(m_szBasePathFile)-2,"%s",lpszBasePathOrFile);
- //查找的是目录还是文件,取得目录名和过滤字符(*.*、*.exe、??.cpp等都是过滤条件)
- char TempBuf[MAX_PATH];
- ZeroMemory(TempBuf,sizeof(TempBuf));
- DWORD dwFileAttrib = GetFileAttributes(m_szBasePathFile);
- if((dwFileAttrib & FILE_ATTRIBUTE_DIRECTORY) && dwFileAttrib != 0xffffffff) //指定搜索一个目录,没有过滤条件
- {
- strcpy(m_strFilter,"*.*");
- if(m_szBasePathFile[iLen - 1] != '\')
- m_szBasePathFile[iLen] = '\';
- }
- else //指定了过滤条件
- {
- PartFileAndPathByFullPath(m_szBasePathFile,m_strFilter,sizeof(m_strFilter),TempBuf,sizeof(TempBuf));
- STRNCPY_SZ( m_szBasePathFile, TempBuf );
- }
- //找相对路径的位置
- if ( !bAbsolutePath )
- {
- strcpy((char*)buf,(const char*)m_szBasePathFile);
- if ( strchr((const char*)buf,':') && strlen((const char*)buf) == 3 ) //是诸如“E:”、“d:”的路径
- {
- m_dwRelativePathStartPos = 3;
- }
- else if ( strlen((const char*)buf) == 1 && buf[0] == '\') //是“”,表示搜索当前盘的根目录
- {
- m_dwRelativePathStartPos = 1;
- }
- else //一般目录(绝对路径、相对路径)
- {
- iLen = (int)strlen((const char*)buf);
- buf[iLen - 1] = ' ';
- p = strrchr((const char*)buf,'\');
- if(p)
- {
- m_dwRelativePathStartPos = (DWORD)(p - buf + 1);
- }
- }
- }
- Dir();
- }
- CHwDir::~CHwDir()
- {
- DeleteStrAry ( &m_pStrAryResFile );
- DeleteStrAry ( &m_pStrArySubDirectory_Private );
- DeleteStrAry ( &m_pStrArySubDirectory );
- }
- /********************************************************************************
- * Function Type : private
- * Parameter : None
- * Return Value : 获得的文件总数
- * Description : 将目录m_szBasePathFile下的所有文件列举出来
- *********************************************************************************/
- DWORD CHwDir::Dir()
- {
- char strDirectory[MAX_PATH*4];
- DWORD dwLine = 0;
- FindDirAndFile(m_szBasePathFile);
- while(1)
- {
- dwLine = (DWORD)m_pStrArySubDirectory_Private->GetSize();
- if(dwLine < 1) break;
- //处理m_StrArySubDirectory中最后一个子目录
- hwSnprintf((char*)strDirectory,sizeof(strDirectory) - 1,"%s",m_pStrArySubDirectory_Private->GetAt(dwLine - 1));
- m_pStrArySubDirectory_Private->RemoveAt(dwLine - 1);
- FindDirAndFile(strDirectory);
- if ( m_bCancel ) break;
- }
- return m_pStrAryResFile->GetSize();
- }
- /********************************************************************************
- * Function Type : private
- * Parameter : lpszDirectory - 要搜索的纯目录
- * Return Value : 获得的文件总数
- * Description : 所有一个目录下的所有目录和符合过滤条件的文件
- *********************************************************************************/
- DWORD CHwDir::FindDirAndFile(LPCTSTR lpszDirectory)
- {
- DWORD dwRet = 0;
- char strDirFile[MAX_PATH*2];
- hwSnprintf((char*)strDirFile,sizeof(strDirFile) - 1,"%s*.*",lpszDirectory); //先搜索出子目录
- dwRet += FindAllFileUnderOneDir((LPCTSTR)strDirFile,lpszDirectory,TRUE);
- hwSnprintf((char*)strDirFile,sizeof(strDirFile) - 1,"%s%s",lpszDirectory,m_strFilter); //再按过滤条件搜索
- dwRet += FindAllFileUnderOneDir(strDirFile,lpszDirectory,FALSE);
- return dwRet;
- }
- /********************************************************************************
- * Function Type : private
- * Parameter : lpszFileName - 要处理的文件(这里把目录也视为文件)
- * lpszDirectory - 纯目录(不需要再找目录了,减少计算量)
- * bFindDir - 是否只搜索目录,不理会文件
- * Return Value : 获得的文件总数
- * Description : 查找lpszFileName指定的所有文件或所有目录
- *********************************************************************************/
- DWORD CHwDir::FindAllFileUnderOneDir(LPCTSTR lpszFileName,LPCTSTR lpszDirectory,BOOL bFindDir)
- {
- DWORD dwFileNum = 0, dwDirNum = 0;
- WIN32_FIND_DATA FindData;
- HANDLE hFileHandle = FindFirstFile(lpszFileName,&FindData);
- if(hFileHandle == INVALID_HANDLE_VALUE)
- return dwFileNum;
- int iRet = HandleOneFile ( lpszDirectory, &FindData, bFindDir );
- if(iRet == 1) //是文件
- dwFileNum ++;
- else if(iRet == 2) //是目录
- dwDirNum ++;
- while ( FindNextFile ( hFileHandle, &FindData ) )
- {
- iRet = HandleOneFile ( lpszDirectory, &FindData, bFindDir );
- if(iRet == 1) //是文件
- dwFileNum ++;
- else if(iRet == 2) //是目录
- dwDirNum ++;
- if ( m_bCancel ) break;
- }
- FindClose(hFileHandle);
- return dwFileNum;
- }
- /********************************************************************************
- * Function Type : private
- * Parameter : lpszDirectory - 纯路径(不包含文件名)
- * pFindData - 文件信息
- * bFindDir - TRUE : 只搜索目录,不理会文件
- * FALSE : 只搜索文件,不理会目录
- * Return Value : 1 - 是一个有效的文件
- * 2 - 是一个有效的目录
- * -1 _ - 不是想要的文件或目录
- * Description : 处理一个找到的文件(这里把目录也视为文件)
- *********************************************************************************/
- int CHwDir::HandleOneFile(LPCTSTR lpszDirectory, WIN32_FIND_DATA* pFindData,BOOL bFindDir)
- {
- char ResBuf[3*MAX_PATH];
- ULONGLONG FileSize;
- LPDWORD pDword = (LPDWORD)&FileSize;
- pDword[0] = pFindData->nFileSizeLow;
- pDword[1] = pFindData->nFileSizeHigh;
- ZeroMemory(ResBuf,sizeof(ResBuf));
- if(stricmp((const char*)pFindData->cFileName,"..")== 0 || pFindData->cFileName[0] == '.')
- return -1;
- if((pFindData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
- pFindData->dwFileAttributes != 0xffffffff)
- {
- if(bFindDir)
- {
- if(m_bSerachSubDir)
- {
- hwSnprintf((char*)ResBuf,sizeof(ResBuf) - 1,"%s%s\",lpszDirectory,pFindData->cFileName);
- m_pStrArySubDirectory_Private->Add((LPCTSTR)ResBuf);
- m_pStrArySubDirectory->Add((LPCTSTR)ResBuf);
- return 2;
- }
- }
- }
- else if(!bFindDir)
- {
- hwSnprintf((char*)ResBuf, sizeof(ResBuf) - 1,
- "%s%s", lpszDirectory+m_dwRelativePathStartPos, pFindData->cFileName );
- m_pStrAryResFile->Add((LPCTSTR)ResBuf);
- m_AmountBytes += FileSize;
- #ifdef _DEBUG
- printf("NO.%04d : %stt%dt字节n",m_pStrAryResFile->GetSize(),ResBuf,FileSize);
- #endif
- return 1;
- }
- return -1;
- }
- /********************************************************************************
- * Function Type : public
- * Parameter : None
- * Return Value : None
- * Description : 取字节总数
- *********************************************************************************/
- ULONGLONG CHwDir::GetAmountBytes()
- {
- return m_AmountBytes;
- }
- void CHwDir::Cancel()
- {
- m_bCancel = TRUE;
- }
- //////////////////////////////////////////////////////////////////////
- // CHwDirEx Class
- //////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- CHwDirEx::CHwDirEx(
- LPCTSTR lpszMultiFindPath, // 要搜索的多路径,如“E:\winnt\;d:temp\;”
- LPCTSTR lpszMultiFindFilter, // 要搜索的过滤条件,如“*.bmp;*.exe;”
- LPCTSTR lpszMultiExcludeFilter/*=NULL*/, // 要排除的过滤条件,如“*.bmp;*.exe;”
- BOOL bSerachSubDir/* = TRUE*/, // 搜索子目录
- BOOL bAbsolutePath /*=TRUE*/, // 是绝对路径
- CHwDirEx **ppHwDirEx/*=NULL*/ // 将这个类的指针传出去给调用者
- )
- : m_AmountBytes ( 0 )
- , m_bCancel ( FALSE )
- , m_pHwDir ( NULL )
- {
- ASSERT ( lpszMultiFindPath && strlen(lpszMultiFindPath) > 0 );
- ASSERT ( lpszMultiFindFilter && strlen(lpszMultiFindFilter) > 0 );
- if ( ppHwDirEx ) *ppHwDirEx = this;
- m_pStrAryResFile = new CStringArray;
- if ( !m_pStrAryResFile ) return;
- m_pStrArySubDirectory = new CStringArray;
- if ( !m_pStrArySubDirectory ) return;
- CStringArray StrAryMultiFindPath;
- PartStringAndAddToStrAry ( (char*)lpszMultiFindPath, StrAryMultiFindPath, (char)f_seps[0] );
- for ( int i=0; i<StrAryMultiFindPath.GetSize(); i++ )
- {
- CString csFindPath = StrAryMultiFindPath.GetAt(i);
- DirAll ( csFindPath, lpszMultiFindFilter, lpszMultiExcludeFilter, bSerachSubDir, bAbsolutePath );
- if ( m_bCancel ) break;
- }
- }
- CHwDirEx::~CHwDirEx()
- {
- DeleteStrAry ( &m_pStrAryResFile );
- DeleteStrAry ( &m_pStrArySubDirectory );
- }
- ULONGLONG CHwDirEx::GetAmountBytes()
- {
- return m_AmountBytes;
- }
- void CHwDirEx::DirAll(
- LPCTSTR lpszFindPath, // 要搜索的路径,如“E:\winnt\”
- LPCTSTR lpszMultiFindFilter, // 要搜索的过滤条件,如“*.bmp;*.exe;”
- LPCTSTR lpszMultiExcludeFilter/*=NULL*/, // 要排除的过滤条件,如“*.bmp;*.exe;”
- BOOL bSerachSubDir/* = TRUE*/, // 搜索子目录
- BOOL bAbsolutePath /*=TRUE*/ // 是绝对路径
- )
- {
- ASSERT ( lpszFindPath && strlen(lpszFindPath) > 0 );
- CStringArray StrAryResFile_Find, StrAryResFile_Exclude,
- StrArySubDirectory_Find, StrArySubDirectory_Exclude;
- DWORD dwAmountBytes_Find = 0, dwAmountBytes_Exclude = 0;
- // 先搜索符合指定过滤条件的文件
- Dir ( lpszFindPath, lpszMultiFindFilter, StrAryResFile_Find, StrArySubDirectory_Find,
- dwAmountBytes_Find, bSerachSubDir, bAbsolutePath );
- // 再搜索需要排除的文件
- if ( lpszMultiExcludeFilter && strlen ( lpszMultiExcludeFilter ) > 0 )
- {
- ASSERT ( lpszMultiExcludeFilter && strlen(lpszMultiExcludeFilter) > 0 );
- Dir ( lpszFindPath, lpszMultiExcludeFilter, StrAryResFile_Exclude, StrArySubDirectory_Exclude,
- dwAmountBytes_Exclude, bSerachSubDir, bAbsolutePath );
- // 然后从 StrAryResFile_Find 中删除掉需要排除的文件
- for ( int i=0; i<StrAryResFile_Exclude.GetSize(); i++ )
- {
- CString csResFile = StrAryResFile_Exclude.GetAt(i);
- int nFindPos = FindFromArray ( StrAryResFile_Find, csResFile );
- if ( nFindPos >= 0 ) StrAryResFile_Find.RemoveAt ( nFindPos );
- if ( m_bCancel ) break;
- }
- }
- // 最后将搜索结果保存到成员变量中,并清理临时变量
- m_pStrAryResFile->Append ( StrAryResFile_Find );
- m_pStrArySubDirectory->Append ( StrArySubDirectory_Find );
- m_AmountBytes += (dwAmountBytes_Find - dwAmountBytes_Exclude);
- StrAryResFile_Find.RemoveAll();
- StrAryResFile_Exclude.RemoveAll();
- StrArySubDirectory_Find.RemoveAll();
- StrArySubDirectory_Exclude.RemoveAll();
- }
- void CHwDirEx::Dir(
- LPCTSTR lpszFindPath, // 要搜索的路径,如“E:\winnt\”
- LPCTSTR lpszMultiFindFilter, // 要搜索的过滤条件,如“*.bmp;*.exe;”
- CStringArray &StrAryResFile, // 搜索的文件保存到此
- CStringArray &StrArySubDirectory, // 搜索的子目录保存到此
- DWORD &dwAmountBytes, // 总字节数保存到此
- BOOL bSerachSubDir/* = TRUE*/, // 搜索子目录
- BOOL bAbsolutePath /*=TRUE*/ // 是绝对路径
- )
- {
- ASSERT ( lpszFindPath && strlen(lpszFindPath) > 0 );
- dwAmountBytes = 0;
- StrAryResFile.RemoveAll();
- StrArySubDirectory.RemoveAll();
- char szFindPath[MAX_PATH] = {0}, szMultiFindFilter[1024]={0}, szMultiExcludeFilter[1024]={0};
- STRNCPY_SZ ( szFindPath, lpszFindPath );
- STRNCPY_SZ ( szMultiFindFilter, lpszMultiFindFilter );
- StandardizationPathBuffer ( szFindPath, sizeof(szFindPath), '\' );
- char *token = strtok( szMultiFindFilter, f_seps );
- while( token != NULL )
- {
- /* While there are tokens in "string" */
- char szFindFile[MAX_PATH] = {0};
- hwSnprintf ( szFindFile, sizeof(szFindFile)-1, "%s%s", szFindPath, token );
- CHwDir dir ( szFindFile, bSerachSubDir, bAbsolutePath, &m_pHwDir );
- if ( dir.m_pStrAryResFile && dir.m_pStrArySubDirectory )
- {
- StrAryResFile.Append ( *(dir.m_pStrAryResFile) );
- StrArySubDirectory.Append ( *(dir.m_pStrArySubDirectory) );
- dwAmountBytes += (DWORD)dir.GetAmountBytes();
- }
- /* Get next token: */
- token = strtok( NULL, f_seps );
- if ( m_bCancel ) break;
- m_pHwDir = NULL;
- }
- }
- void CHwDirEx::Cancel()
- {
- m_bCancel = TRUE;
- if ( m_pHwDir )
- m_pHwDir->Cancel ();
- }
- CString GetOneLine(CString &str)
- {
- int nPos = str.Find ( "rn", 0 );
- if ( nPos < 0 ) return "";
- CString csOneLine = str.Left ( nPos );
- str = str.Mid ( nPos + 2 );
- return csOneLine;
- }
- int CalcCharCount ( LPCTSTR lpszText, char chCalc )
- {
- int nLen = STRLEN_SZ(lpszText);
- int nCount = 0;
- for ( int i=0; i<nLen; i++ )
- {
- if ( (BYTE)lpszText[i] == (BYTE)chCalc )
- nCount ++;
- }
- return nCount;
- }
- #define TIME_START_YEAR 1900
- BOOL CopyBuffer_Date ( int *data, SYSTEMTIME &SysTime )
- {
- const int nMinDateDigitCount = 3;
- ASSERT_ADDRESS ( data, nMinDateDigitCount * sizeof(int) );
- /********年(1000 ~ 9999)********/
- if ( data[0] < 1000 || data[0] >= 9999 )
- return FALSE;
- SysTime.wYear = data[0];
- /********月(1--12)********/
- if ( data[1] < 1 || data[1] > 12 )
- return FALSE;
- SysTime.wMonth = data[1];
- /********日(1--31)********/
- if ( data[2] < 1 && data[2] > 31 )
- return FALSE;
- SysTime.wDay = data[2];
- return TRUE;
- }
- BOOL CopyBuffer_Time ( int *data, SYSTEMTIME &SysTime )
- {
- const int nMinDateDigitCount = 3;
- ASSERT_ADDRESS ( data, nMinDateDigitCount * sizeof(int) );
- /********时(0--23)********/
- if ( data[0] <0 || data[0] > 23 )
- return FALSE;
- SysTime.wHour = data[0];
- /********分(0--59)********/
- if ( data[1] < 0 || data[1] > 59 )
- return FALSE;
- SysTime.wMinute = data[1];
- /********秒********/
- if ( data[2] < 0 || data[2] > 59 )
- return FALSE;
- SysTime.wSecond = data[2];
- return TRUE;
- }
- //
- // ConvertStrToCTime() 将一个表示日期的字符串(按年、月、日、时、分、秒的顺序,
- // 如"2001-08-09 18:03:30")转成 CTime 格式.
- // return : ------------------------------------------------------------
- // 0 - 错误
- // 1 - 是时期时间
- // 2 - 是日期
- // 3 - 是时间
- //
- int ConvertStrToCTime(char *chtime, CTime &cTime )
- {
- int i, j, k;
- char tmpbuf[8] = {0};
- int value[6] = {0};
- SYSTEMTIME SysTime = {0};
- if ((!chtime) ) return FALSE; /* invalid parameter */
- memset((void *)value, 0, sizeof(value));
- for (i=0, j=0, k=0; ; i++)
- {
- if (chtime[i]<'0' || chtime[i]>'9') /* 非数字字符 */
- {
- tmpbuf[j] = ' ';
- if ( j > 0 )
- {
- value[k++] = atoi(tmpbuf);
- j = 0;
- if ( k >= 6 ) break;
- }
- if ( chtime[i] == ' ' ) break;
- }
- else if (j < 7) tmpbuf[j++] = chtime[i];
- }
- if ( k < 3 ) return 0;
- if (
- CalcCharCount ( chtime, '-' ) < 2
- &&
- CalcCharCount ( chtime, '/' ) < 2
- &&
- CalcCharCount ( chtime, ':' ) < 2
- )
- return 0;
- int nRet = 0;
- // 是日期时间
- if (
- ( k>=6 )
- &&
- CopyBuffer_Date ( value, SysTime )
- &&
- CopyBuffer_Time ( &value[3], SysTime )
- )
- {
- nRet = 1;
- }
- // 是日期
- else if (
- (k>=3)
- &&
- CopyBuffer_Date ( value, SysTime )
- )
- {
- nRet = 2;
- }
- // 是时间
- if (
- (k>=3)
- &&
- CopyBuffer_Time ( value, SysTime )
- )
- {
- nRet = 3;
- }
-
- if ( SysTime.wYear < 1971 )
- SysTime.wYear = 1971;
- if ( SysTime.wMonth < 1 )
- SysTime.wMonth = 1;
- if ( SysTime.wDay < 1 )
- SysTime.wDay = 1;
- CTime tTemp ( SysTime );
- cTime = tTemp;
- return nRet;
- }
- void Log ( UINT nLevel, LPCTSTR lpszFormat, ... )
- {
- // 格式化
- char szLogBuf[1024] = {0};
- va_list va;
- va_start (va, lpszFormat);
- _vsnprintf ( szLogBuf, sizeof(szLogBuf)-1, (const char*)lpszFormat, va);
- va_end(va);
- UINT nType = MB_ICONWARNING;
- nLevel &= 0x0f;
- if ( nLevel == L_VERBOSE || nLevel == L_NORMAL )
- nType = MB_ICONINFORMATION;
- else if ( nLevel == L_ERROR )
- nType = MB_ICONERROR;
- AfxMessageBox ( szLogBuf, nType );
- }
- /********************************************************************************
- * Function Type : public
- * Parameter : buf - 输出缓冲
- * Return Value : 字符个数
- * Description : 获取当前时间的字符串,如:2003-10-01 12:00:00
- *********************************************************************************/
- DWORD GetCurTimeString ( char *buf, time_t tNow/*=0*/ )
- {
- ASSERT_ADDRESS ( buf, DATETIME_TYPE_LENGTH );
- if ( tNow == 0 ) tNow = time(NULL);
- CTime cTime ( tNow );
- CString csNow = cTime.Format ( "%Y-%m-%d %H:%M:%S" );
- return (DWORD)hwSnprintf ( buf, DATETIME_TYPE_LENGTH, "%s", csNow );
- }
- CCriticalSection f_CSFor_DbgLog;
- void DbgLog ( LPCTSTR lpszFormat, ... )
- {
- // 格式化
- f_CSFor_DbgLog.Lock ();
- char szLogBuf[1024*4] = {0};
- char *p = szLogBuf;
- *p = '[';
- p ++;
- char szTime[32] = {0};
- int nLen = (int)GetCurTimeString ( szTime, sizeof(szTime) );
- strcpy ( p, szTime );
- p += nLen;
- *p = ']';
- p ++;
- *p = ' ';
- p ++;
-
- va_list va;
- va_start (va, lpszFormat);
- _vsnprintf ( p, sizeof(szLogBuf)-1-(int)(p-szLogBuf), (const char*)lpszFormat, va);
- va_end(va);
- WriteDataToFile ( "c:\debug.txt", szLogBuf, strlen(szLogBuf), "ab+" );
- f_CSFor_DbgLog.Unlock ();
- }
- int GetMouthByShortStr ( LPCTSTR lpszShortMonth )
- {
- const char* szConstMonth[] =
- {
- "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", ""
- };
- CString csShortMonth = GET_SAFE_STRING ( lpszShortMonth );
- for ( int i=0; i<sizeof(szConstMonth)/sizeof(szConstMonth[0]); i++ )
- {
- if ( csShortMonth.CompareNoCase ( szConstMonth[i] ) == 0 )
- {
- return ( i+1 );
- }
- }
- return -1;
- };
- CString hwFormatMessage ( DWORD dwErrorCode )
- {
- CString csError;
- LPVOID pv;
- FormatMessage (
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- dwErrorCode,
- MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
- (LPTSTR)&pv,
- 0,
- NULL);
- if(pv)
- {
- csError = (char*)pv;
- LocalFree ( pv );
- }
- return csError;
- }
- /********************************************************************************
- * Function Type : Global
- * Parameter : filename - 文件名
- * data - 要保存的数据
- * mode - 文件打开的模式
- * size - 数据大小
- * nStartPos - 文件开始位置
- * Return Value : >=0 - 写入文件的大小
- * -1 - 写操作失败
- * Description : 保存数据到文件
- *********************************************************************************/
- int WriteDataToFile(LPCTSTR filename,char* data,long size,LPCTSTR mode, int nStartPos/*=-1*/ )
- {
- ASSERT ( filename && strlen(filename) > 0 );
- FILE *fp;
- long retval;
- fp=fopen((const char*)filename,(const char*)mode);
- if ( fp!=NULL)
- {
- if ( nStartPos >= 0 )
- {
- if ( fseek ( fp, nStartPos, SEEK_SET ) != 0 )
- return -1;
- }
- retval = (long)fwrite(data,sizeof(UCHAR),size,fp);
- fclose(fp);
- if(retval != size)
- {
- return -1;
- }
- else return retval;
- }
- else
- {
- return -1;
- }
- }
- /********************************************************************************
- * Function Type : Global
- * Parameter : filename - 文件名
- * data - 读到的数据存于此缓冲
- * size - 缓冲大小
- * nStartPos - 文件开始位置
- * Return Value : >=0 - 读到数据的大小
- * -1 - 操作失败
- * Description : 从文件中读取数据
- *********************************************************************************/
- int ReadDataFromFile(LPCTSTR filename,char* data,long size, int nStartPos/*=-1*/)
- {
- FILE *fp;
- long retval;
- fp=fopen((const char*)filename,"rb");
- if ( fp!=NULL)
- {
- if ( nStartPos >= 0 )
- {
- if ( fseek ( fp, nStartPos, SEEK_SET ) != 0 )
- return -1;
- }
- retval = (long)fread(data,sizeof(char), size, fp);
- fclose(fp);
- if ( retval >= 0 ) return retval;
- }
- return -1;
- }
- CString Data2HexString ( int nOffset, char *data, int size )
- {
- CString csHexString, csTemp, csOffset;
- if ( nOffset >= 0 )
- {
- csOffset.Format ( "%08xh: ", nOffset );
- csHexString += csOffset;
- }
- for ( int i=0; i<size; i++ )
- {
- csTemp.Format ( "%02X ", (BYTE)data[i] );
- csHexString += csTemp;
- if ( (i+1) % 16 == 0 )
- {
- csHexString += "rn";
- if ( nOffset >= 0 )
- {
- nOffset += 16;
- csOffset.Format ( "%08xh: ", nOffset );
- csHexString += csOffset;
- }
- }
- }
- return csHexString;
- }
- //
- // 为了方便 strchr() 或 strrchr() 函数正确查找字符,将字符串中的中文字符串用指定的字符替换掉
- //
- void ReplaceChineseStrToEnglish ( char *szBuf, char cReplace )
- {
- if ( !szBuf ) return;
- for ( int i=0; szBuf[i] != ' '; i++ )
- {
- if ( szBuf[i] < 0 && szBuf[i+1] != ' ' )
- {
- szBuf[i] = cReplace;
- szBuf[i+1] = cReplace;
- i ++;
- }
- }
- }
- /********************************************************************************
- * Function Type : Global
- * Parameter : lpszDirName - [in] 目录名
- * Return Value : 没有路径的文件名
- * Description : 确保路径存在,如果目录不存在就创建目录,可以创建多层次的目录
- *********************************************************************************/
- char* MakeSureDirectory(LPCTSTR lpszDirName)
- {
- char tempbuf[255];
- char *p1 = NULL, *p2 = (char*)lpszDirName;
- int len;
- while(1)
- {
- p1 = hwStrChr((const char*)p2,'\');
- if( p1 )
- {
- ZeroMemory(tempbuf,sizeof(tempbuf));
- len = (int)((p1 - lpszDirName > sizeof(tempbuf)) ? sizeof(tempbuf) : (p1 - lpszDirName));
- if(len < 1) //如:“123456”目录,第一个就是“”
- {
- p2 = p1 + 1;
- continue;
- }
- strncpy((char*)tempbuf,(const char*)lpszDirName, len);
- if(_access((const char*)tempbuf,0) == -1) //Not exist
- {
- if(_mkdir((const char*)tempbuf) != 0)
- return FALSE;
- }
- p2 = p1 + 1;
- }
- else break;
- }
-
- return p2;
- }
- int hwSnprintf ( char *buffer, int count, const char *format, ... )
- {
- if ( count < 1 ) return 0;
- ASSERT_ADDRESS ( buffer, count );
- memset ( buffer, 0, count );
- // 格式化
- va_list va;
- va_start (va, format);
- int nRet = _vsnprintf ( buffer, count, (const char*)format, va);
- va_end(va);
- buffer [count-1] = ' ';
- int nLen = nRet;
- if ( nLen < 0 ) nLen = strlen(buffer);
- if ( nLen > count ) nLen = count;
- return nLen;
- }
- //
- //
- // 从一个完整的全路径名(包含文件名)中分离出路径(没有文件名)和
- // 文件名,如:从“E: 01 02.exe”中分得“E: 01”,结果存入到
- // lsOnlyPath中,“002.exe”存入szOnlyFileName中
- //
- BOOL PartFileAndPathByFullPath (
- IN LPCTSTR lpszFilePath, // 全路径名(包含文件名)
- OUT char *szOnlyFileName, // 光文件名(没有路径)
- int nFileNameSize,
- OUT char *szOnlyPath /*=NULL*/, // 光路径(没有文件名)
- int nPathSize/*=0*/
- )
- {
- ASSERT ( lpszFilePath );
- char chDirPart = '\';
- if ( hwStrChr ( lpszFilePath, '/' ) )
- chDirPart = '/';
- if ( szOnlyFileName )
- {
- memset ( szOnlyFileName, 0, nFileNameSize );
- }
- if ( szOnlyPath )
- {
- memset ( szOnlyPath, 0, nPathSize );
- }
-
- WIN32_FILE_ATTRIBUTE_DATA FileAttrData;
- if ( GetFileAttributesEx ( lpszFilePath, GetFileExInfoStandard, (LPVOID)&FileAttrData ) &&
- ( FileAttrData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) == FILE_ATTRIBUTE_DIRECTORY
- && FileAttrData.dwFileAttributes != 0xffffffff ) // 本身就是目录
- {
- if ( szOnlyPath )
- {
- STRNCPY ( szOnlyPath, lpszFilePath, nPathSize );
- StandardizationPathBuffer ( szOnlyPath, nPathSize, chDirPart );
- }
- return TRUE;
- }
- char *p = hwStrrChr ( lpszFilePath, chDirPart );
- if ( !p )
- {
- STRNCPY ( szOnlyFileName, lpszFilePath, nFileNameSize );
- return TRUE;
- }
- if ( szOnlyFileName )
- STRNCPY ( szOnlyFileName, p+1, nFileNameSize );
- if ( szOnlyPath )
- {
- STRNCPY ( szOnlyPath, lpszFilePath, nPathSize );
- int nLen = p-lpszFilePath+1;
- if ( nPathSize-1 < nLen ) return FALSE;
- szOnlyPath [ nLen ] = ' ';
- }
- return TRUE;
- }
- BOOL PartPathAndFileAndExtensionName (
- IN LPCTSTR lpszFilePath, // 全路径名(包含文件名)
- OUT CString *pcsOnlyPath, // 输出光路径(没有文件名)
- OUT CString *pcsOnlyFileName, // 输出光文件名(没有路径)
- OUT CString *pcsExtensionName // 输出扩展名
- )
- {
- char szOnlyPath[MAX_PATH] = {0};
- char szOnlyFileName[MAX_PATH] = {0};
- char szExtensionName[MAX_PATH] = {0};
- if ( !PartFileAndPathByFullPath ( lpszFilePath, szOnlyFileName, MAX_PATH, szOnlyPath, MAX_PATH ) )
- return FALSE;
- if ( !PartFileAndExtensionName ( szOnlyFileName, szOnlyFileName, MAX_PATH, szExtensionName, MAX_PATH ) )
- return FALSE;
- if ( pcsOnlyPath ) *pcsOnlyPath = szOnlyPath;
- if ( pcsOnlyFileName ) *pcsOnlyFileName = szOnlyFileName;
- if ( pcsExtensionName ) *pcsExtensionName = szExtensionName;
- return TRUE;
- }
- char *hwStrrChr ( const char *string, int c )
- {
- if ( !string ) return NULL;
- CString csString = string;
- ReplaceChineseStrToEnglish ( csString.GetBuffer(0), (c>=127) ? (c-1) : (c+1) );
- csString.ReleaseBuffer ();
- int nPos = csString.ReverseFind ( c );
- if ( nPos < 0 ) return NULL;
- return ( (char*)string + nPos );
- }
- char *hwStrChr ( const char *string, int c )
- {
- if ( !string ) return NULL;
- CString csString = string;
- ReplaceChineseStrToEnglish ( csString.GetBuffer(0), (c>=127) ? (c-1) : (c+1) );
- csString.ReleaseBuffer ();
- int nPos = csString.Find ( c );
- if ( nPos < 0 ) return NULL;
- return ( (char*)string + nPos );
- }
- //
- // 根据文件名来找它的文件名和扩展名,如:完整路径为“E:123456.bmp”,那么 szFileName 等于“E:123456”
- // szExtensionName 等于“bmp”
- //
- BOOL PartFileAndExtensionName (
- IN LPCTSTR lpszFileName,
- OUT char *szFileName,
- IN int nFileNameSize,
- OUT char *szExtensionName/*=NULL*/,
- IN int nExtensionNameSize/*=0*/ )
- {
- ASSERT ( lpszFileName );
- char chDirPart = '\';
- if ( hwStrChr ( lpszFileName, '/' ) )
- chDirPart = '/';
- if ( szFileName )
- {
- STRNCPY ( szFileName, lpszFileName, nFileNameSize );
- }
- if ( szExtensionName )
- {
- memset ( szExtensionName, 0, nExtensionNameSize );
- }
- char *p_Dot = hwStrrChr ( lpszFileName, '.' );
- if ( !p_Dot )
- {
- return TRUE;
- }
- char *p_Slash = hwStrrChr ( lpszFileName, chDirPart );
- if ( szFileName )
- {
- if ( p_Dot-lpszFileName >= nFileNameSize )
- return FALSE;
- // TRACE ( "%d, %dn", p_Dot-lpszFileName, strlen(lpszFileName) );
- if ( int(p_Dot-lpszFileName) < (int)strlen(lpszFileName)-1 )
- szFileName [p_Dot-lpszFileName] = ' ';
- }
- if ( p_Slash > p_Dot )
- {
- return TRUE;
- }
- if ( szExtensionName )
- {
- STRNCPY ( szExtensionName, p_Dot+1, nExtensionNameSize );
- }
- return TRUE;
- }
- //
- // 删除一个文件夹,不管里面有没有文件,都会被删除
- //
- BOOL hwDeleteFolder ( LPCTSTR lpszFolder )
- {
- BOOL bRet = FALSE;
- CHwDir dir ( lpszFolder, TRUE, TRUE );
- if ( !dir.m_pStrAryResFile || !dir.m_pStrArySubDirectory )
- return FALSE;
- for ( int i=0; i<dir.m_pStrAryResFile->GetSize(); i++ )
- {
- CString csFileName = dir.m_pStrAryResFile->GetAt ( i );
- bRet = ::SetFileAttributes ( csFileName, FILE_ATTRIBUTE_NORMAL );
- bRet = ::DeleteFile ( csFileName );
- if ( !bRet )
- {
- DWORD dwLastError = ::GetLastError ();
- }
- }
- for ( i=dir.m_pStrArySubDirectory->GetSize()-1; i>=0; i-- )
- {
- CString csDirName = dir.m_pStrArySubDirectory->GetAt ( i );
- TRACE ( "Delete dir : %sn", csDirName );
- bRet = ::SetFileAttributes ( csDirName, FILE_ATTRIBUTE_NORMAL );
- bRet = RemoveDirectory ( csDirName );
- }
-
- return RemoveDirectory ( lpszFolder );
- }
- //
- // 将一个文件追加拷贝到另一个文件末尾
- //
- BOOL CopyFileAppend ( LPCTSTR lpszFileName_Src, LPCTSTR lpszFileName_Dst, int nOffset )
- {
- if ( !lpszFileName_Src || !lpszFileName_Dst ) return FALSE;
- CFileStatus fileStatus;
- if ( !CFile::GetStatus(lpszFileName_Src,fileStatus) || fileStatus.m_size < 1 )
- {
- return TRUE;
- }
- const int nBufSize = 1024*1024;
- char *pTempBuf = new char[nBufSize];
- if ( !pTempBuf ) return FALSE;
- BOOL bRet = FALSE;
- CFile file_Src, file_Dst;
- TRY
- {
- if ( file_Src.Open ( lpszFileName_Src, CFile::modeRead|CFile::typeBinary ) &&
- file_Dst.Open ( lpszFileName_Dst, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite|CFile::typeBinary ) )
- {
- if ( nOffset >= 0 )
- {
- file_Dst.Seek ( nOffset, CFile::begin );
- }
- else
- {
- file_Dst.SeekToEnd ();
- }
- int nReadSize = 0;
- while ( (nReadSize = file_Src.ReadHuge ( pTempBuf, nBufSize )) > 0 )
- {
- file_Dst.WriteHuge ( pTempBuf, nReadSize );
- }
- bRet = TRUE;
- }
- }
- CATCH( CFileException, e )
- {
- e->Delete ();
- bRet = FALSE;
- }
- END_CATCH
- if ( pTempBuf ) delete[] pTempBuf;
- if ( HANDLE_IS_VALID(file_Src.m_hFile) )
- file_Src.Close ();
- if ( HANDLE_IS_VALID(file_Dst.m_hFile) )
- file_Dst.Close ();
- return bRet;
- }
- //
- // 创建一个空文件
- //
- BOOL CreateNullFile ( LPCTSTR lpszFileName, int nFileSize )
- {
- if ( !lpszFileName ) return FALSE;
- DeleteFile ( lpszFileName );
- CFile file;
- BOOL bRet = TRUE;
- TRY
- {
- bRet = file.Open ( lpszFileName, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary );
- if ( bRet && nFileSize > 0 )
- file.SetLength ( nFileSize );
- }
- CATCH( CFileException, e )
- {
- e->Delete ();
- bRet = FALSE;
- }
- END_CATCH
- if ( !bRet )
- {
- Log ( L_WARNING, "Create file [%s] failed. %s", lpszFileName, hwFormatMessage ( GetLastError() ) );
- }
- if ( HANDLE_IS_VALID(file.m_hFile) )
- file.Close ();
- return bRet;
- }
- //
- // 等待线程退出
- //
- BOOL WaitForThreadEnd ( HANDLE hThread, DWORD dwWaitTime /*=5000*/ )
- {
- BOOL bRet = TRUE;
- if ( !HANDLE_IS_VALID(hThread) ) return TRUE;
- if ( ::WaitForSingleObject ( hThread, dwWaitTime ) == WAIT_TIMEOUT )
- {
- bRet = FALSE;
- ::TerminateThread ( hThread, 0 );
- }
- return bRet;
- }
- /********************************************************************************
- * Function Type : Global
- * Parameter : lpszPathName - [out] 选择的路径名
- * Return Value : 路径字符数
- * Description : 从通用对话框中选择路径
- * Note : 缓冲lpszPathName申请时建议大小为“MAX_PATH”
- *********************************************************************************/
- DWORD SelectPathByCommonDlg(LPSTR lpszPathName,HWND hwndOwner/*=NULL*/)
- {
- ASSERT_ADDRESS ( lpszPathName, MAX_PATH );
- DWORD dwLength = 0;
- LPMALLOC pMalloc; //利用shell的扩展功能
- BROWSEINFO bi;
- if ( !SUCCEEDED(SHGetMalloc(&pMalloc)) ) //为生成目录选择对话框分配内存
- return 0;
- ZeroMemory( (char*)&bi, sizeof(bi) );
- LPITEMIDLIST pidl;
- bi.hwndOwner = hwndOwner;
- bi.pidlRoot = NULL;
- bi.pszDisplayName = (LPSTR)lpszPathName;
- bi.lpszTitle = _T("Select Directory");
- bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
- bi.lpfn = NULL;
- bi.lParam = 0;
- if ( (pidl = ::SHBrowseForFolder(&bi)) != NULL)//调用选择目录对话框
- {
- // 获得所选择的目录
- if ( ::SHGetPathFromIDList(pidl, (LPSTR)lpszPathName) )
- {
- dwLength = (DWORD)strlen((const char*)lpszPathName);
- if(lpszPathName[dwLength-1] != '\')
- {
- strcat((char*)lpszPathName,"\");
- dwLength ++;
- }
- }
- pMalloc->Free(pidl);//释放分配的资源
- }
- pMalloc->Release();
- return dwLength;
- }
- BOOL SelectPathByCommonDlg ( CWnd *pDlg, UINT nEditID )
- {
- if ( !pDlg || nEditID < 1 ) return FALSE;
- char szPath[MAX_PATH] = {0};
- if ( SelectPathByCommonDlg ( szPath, pDlg->GetSafeHwnd() ) > 0 )
- {
- pDlg->SetDlgItemText ( nEditID, szPath );
- return TRUE;
- }
- return FALSE;
- }
- //
- // 标准化路径缓冲,如果不是以“”结尾,将自动加上
- //
- void StandardizationPathBuffer ( char *szPath, int nSize, char cFlagChar/*='\'*/ )
- {
- int nLen = strlen(szPath);
- if ( nLen < 1 ) return;
- ASSERT_ADDRESS ( szPath, nLen+1 );
- char szTemp[4] = {0};
- szTemp[0] = cFlagChar;
- if ( szPath[nLen-1] != cFlagChar )
- strncat ( szPath, szTemp, nSize );
- CString csPath = StandardizationFileForPathName ( szPath, FALSE );
- strncpy ( szPath, csPath, nSize );
- }
- //
- // 标准化路径或文件名,把不符合文件名命名规则的字符替换成指定的字符。//u 在 StandardizationPathBuffer() 中
- // 加上该函数
- //
- CString StandardizationFileForPathName ( LPCTSTR lpszFileOrPathName, BOOL bIsFileName, char cReplaceChar/*='_'*/ )
- {
- CString csFileOrPathName = GET_SAFE_STRING(lpszFileOrPathName);
- CString csHead, csTail;
- // 路径名中最后一个'\'是正常的。另外类似“c:\”的字符也是正常的。所以先提取出来不参与后面的替换,等替换完以后再补回来
- if ( !bIsFileName )
- {
- if ( csFileOrPathName.GetLength() >= 1 && (csFileOrPathName[csFileOrPathName.GetLength()-1] == '\' || csFileOrPathName[csFileOrPathName.GetLength()-1] == '/') )
- {
- csTail += csFileOrPathName[csFileOrPathName.GetLength()-1];
- csFileOrPathName = csFileOrPathName.Left ( csFileOrPathName.GetLength()-1 );
- }
- if ( csFileOrPathName.GetLength() >= 2 && isalpha(csFileOrPathName[0]) && csFileOrPathName[1]==':' )
- {
- csHead = csFileOrPathName.Left(2);
- csFileOrPathName = csFileOrPathName.Mid(2);
- }
- if ( csFileOrPathName.GetLength() >= 1 && (csFileOrPathName[0]=='\' || csFileOrPathName[0]=='/') )
- {
- csHead += csFileOrPathName[0];
- csFileOrPathName = csFileOrPathName.Mid(1);
- }
- }
- csFileOrPathName.Replace ( "\", "_" );
- csFileOrPathName.Replace ( "/", "_" );
- csFileOrPathName.Replace ( ":", "_" );
- csFileOrPathName.Replace ( "*", "_" );
- csFileOrPathName.Replace ( "?", "_" );
- csFileOrPathName.Replace ( """, "_" );
- csFileOrPathName.Replace ( "<", "_" );
- csFileOrPathName.Replace ( ">", "_" );
- csFileOrPathName.Replace ( "|", "_" );
- csFileOrPathName.Insert ( 0, csHead );
- csFileOrPathName += csTail;
- return csFileOrPathName;
- }