FileBase.cpp
资源名称:GGBT.rar [点击查看]
上传用户:lds876
上传日期:2013-05-25
资源大小:567k
文件大小:13k
源码类别:
P2P编程
开发平台:
Visual C++
- // FileBase.cpp: implementation of the FileBase class.
- //
- //////////////////////////////////////////////////////////////////////
- #include "stdafx.h"
- #include "testbt.h"
- #include "FileBase.h"
- #ifdef _DEBUG
- #undef THIS_FILE
- static char THIS_FILE[]=__FILE__;
- #define new DEBUG_NEW
- #endif
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- bool CopyTextToClipboard(CString strSource)
- {
- bool bRet = true;
- // put strSource to clipboard.
- if(OpenClipboard(NULL))
- {
- EmptyClipboard();
- HGLOBAL clipbuffer = GlobalAlloc(GMEM_DDESHARE, strSource.GetLength()+1);
- if (clipbuffer)
- {
- char * buffer = (char*)GlobalLock(clipbuffer);
- if (buffer)
- {
- strcpy(buffer, LPCSTR(strSource));
- GlobalUnlock(clipbuffer);
- SetClipboardData(CF_TEXT,clipbuffer);
- }
- else
- bRet = false;
- }
- else
- bRet = false;
- CloseClipboard();
- }
- else
- bRet = false;
- return true;
- }
- string FormatSizeK(BLONG lSize, bool bFloat)
- {
- assert(lSize >= 0);
- char szText[100] = {0};
- float lposition = (float)lSize/1024;
- if (bFloat)
- sprintf(szText, "%.2fK", lposition);
- else
- sprintf(szText, "%.0fK", lposition);
- return string(szText);
- }
- string FormatSizeM(BLONG lSize, bool bFloat)
- {
- assert(lSize >= 0);
- char szText[100] = {0};
- float lposition = (float)lSize/1024/1024;
- if (bFloat)
- sprintf(szText, "%.2fM", lposition);
- else
- sprintf(szText, "%.0fM", lposition);
- return string(szText);
- }
- string FormatSize(BLONG lSize, bool bFloat)
- {
- assert(lSize >= 0);
- char szText[100] = {0};
- float lposition = (float)lSize/1024/1024/1024;
- if (lposition >= 1)
- {
- if (bFloat)
- sprintf(szText, "%.2fG", lposition);
- else
- sprintf(szText, "%.0fG", lposition);
- return string(szText);
- }
- lposition = (float)lSize/1024/1024;
- if (lposition >= 1)
- {
- if (bFloat)
- sprintf(szText, "%.2fM", lposition);
- else
- sprintf(szText, "%.0fM", lposition);
- return string(szText);
- }
- lposition = (float)lSize/1024;
- if (lposition >= 1)
- {
- if (bFloat)
- sprintf(szText, "%.2fK", lposition);
- else
- sprintf(szText, "%.0fK", lposition);
- return string(szText);
- }
- sprintf(szText, "%dB", lSize);
- return string(szText);
- }
- long GetFileSize(string strFileName)
- {
- FILE* pfile = fopen(strFileName.data(), "rb");
- if (!pfile)
- {
- // assert(false);
- return 0;
- }
- int iRet = fseek(pfile, 0, SEEK_END);
- if (iRet)
- {
- assert(false);
- return 0;
- }
- long lsize = ftell(pfile);
- fclose(pfile);
- assert(lsize >= 0);
- return lsize;
- }
- bool MakesureFileCreate(string strFilePath)
- {
- char drive[_MAX_DRIVE];
- char dir[_MAX_DIR];
- char fname[_MAX_FNAME];
- char ext[_MAX_EXT];
- _splitpath(strFilePath.data(), drive, dir, fname, ext);
- if (!strlen(drive))
- return false;
- string strDir = drive;
- strDir += dir;
- if (strDir[strDir.size() - 1] != '\')
- strDir += '\';
- if (!MakeDirecotry(strDir))
- return false;
- return true;
- }
- bool MakeDirecotry(string strDir)
- {
- if (strDir.empty())
- return false;
- // make sure directory is absolute path.
- char drive[_MAX_DRIVE];
- char dir[_MAX_DIR];
- char fname[_MAX_FNAME];
- char ext[_MAX_EXT];
- _splitpath(strDir.data(), drive, dir, fname, ext);
- if (!strlen(drive))
- return false;
- CString strPath = strDir.data();
- int i = 0;
- while (true)
- {
- i = strPath.Find('\', i+1);
- if (i == -1)
- break;
- string strTemp = strPath.Left(i);
- if (!CreateDirectory(strTemp.data(), 0))
- {
- /*
- DWORD dwErr = GetLastError();
- if (dwErr != ERROR_ALREADY_EXISTS)
- return false;
- //*/
- }
- }
- if (!CreateDirectory(strDir.data(), 0))
- {
- DWORD dwErr = GetLastError();
- if (dwErr != ERROR_ALREADY_EXISTS && dwErr != ERROR_ACCESS_DENIED)
- return false;
- }
- return true;
- }
- string formatDir(string strDir)
- {
- assert(!strDir.empty());
- string strRet;
- if (strDir[strDir.size() - 1] != '\')
- strDir += '\';
- return strDir;
- }
- static m_gMovingFiles = 0;
- int IsMovingFiles()
- {
- return m_gMovingFiles;
- }
- bool MoveDiretorySystem(vector<CString> vstrOld, CString strNew, HWND hWnd)
- {
- if (vstrOld.empty())
- {
- assert(false);
- return false;
- }
- DWORD dwAttr = GetFileAttributes(strNew);
- if (dwAttr == 0xffffffff)
- {
- if (!MakeDirecotry(strNew.GetBuffer(0)))
- {
- assert(false);
- return false;
- }
- }
- //
- // Create the target dir, else move not create name dir.
- //
- char pstrOld[1024] = {0};
- char pstrNew[1024] = {0};
- memset(pstrOld, 0, 1024);
- memset(pstrNew, 0, 1024);
- char* pTempOld = pstrOld;
- char* pTempNew = pstrNew;
- bool bEmpty = true;
- for (int i=0; i<vstrOld.size(); i++)
- {
- CString strOld = vstrOld[i];
- string strName, strPath;
- SplitPathName(strOld.GetBuffer(0), strPath, strName);
- if (formatDir(strPath) == formatDir(strNew.GetBuffer(0)) )
- {
- // assert(false);
- // return true;
- continue;
- }
- strcpy(pTempOld, strOld.GetBuffer(0));
- strcpy(pTempNew, strNew.GetBuffer(0));
- pTempOld += strlen(pTempOld) + 1;
- pTempNew += strlen(pTempNew) + 1;
- bEmpty = false;
- }
- if (bEmpty)
- {
- assert(false);
- return true;
- }
- SHFILEOPSTRUCT shFileOp;
- shFileOp.fAnyOperationsAborted = FALSE;
- shFileOp.lpszProgressTitle = "正在移动...";
- shFileOp.hwnd = hWnd;
- shFileOp.wFunc = FO_MOVE;
- shFileOp.pFrom = pstrOld;
- shFileOp.pTo = pstrNew;
- shFileOp.fFlags = FOF_ALLOWUNDO;// | FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE | ;
- shFileOp.hNameMappings = 0;
- m_gMovingFiles ++;
- int iRet = SHFileOperation(&shFileOp);
- m_gMovingFiles --;
- // WaitForSingleObject((HANDLE)iRet, 50000);
- //*/
- /*
- if(iRet)
- {
- shFileOp.pFrom = b;
- shFileOp.pTo = a;
- int iRet = SHFileOperation(&shFileOp);
- ASSERT(!iRet);
- }
- //*/
- // return shFileOp.fAnyOperationsAborted == false;
- return iRet == 0;
- }
- bool MoveDiretory(string strOld, string strNew)
- {
- strOld = formatDir(strOld);
- strNew = formatDir(strNew);
- if (_access(strOld.data(), 0))
- return true;
- if (strOld == strNew)
- return true;
- if (MoveFile(strOld.data(), strNew.data()))
- {
- assert(false);
- return true;
- }
- if (!MakeDirecotry(strNew))
- return false;
- WIN32_FIND_DATA FileData; // Data structure describes the file found
- HANDLE hSearch; // Search handle returned by FindFirstFile
- TCHAR szMsg[100]; // String to store the error message
- BOOL bFinished = FALSE;
- hSearch = FindFirstFile ((strOld + "*.*").data(), &FileData);
- if (hSearch == INVALID_HANDLE_VALUE)
- {
- wsprintf (szMsg, TEXT("No .TXT files found."));
- return true;
- }
- // Copy each .txt file to the new directory and change it to
- // read-only, if it is not already read-only.
- while (!bFinished)
- {
- string strNewPath = strNew + FileData.cFileName;
- string strOldPath = strOld + FileData.cFileName;
- if (!(FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
- {
- if (!CopyFile (strOldPath.data(), strNewPath.data(), FALSE))
- {
- DWORD dwErr = GetLastError();
- // maybe the parent dir have subdir has the same name with the file, fail silently.
- if (dwErr != ERROR_ACCESS_DENIED)
- {
- wsprintf (szMsg, TEXT("Unable to copy file."));
- return false;
- }
- }
- }
- if (!FindNextFile (hSearch, &FileData))
- {
- bFinished = TRUE;
- if (GetLastError () == ERROR_NO_MORE_FILES)
- {
- wsprintf (szMsg, TEXT("Found all of the files."));
- return true;
- }
- else
- {
- wsprintf (szMsg, TEXT("Unable to find next file."));
- return false;
- }
- }
- }
- // Close the search handle.
- if (!FindClose (hSearch))
- {
- wsprintf (szMsg, TEXT("Unable to close search handle."));
- return false;
- }
- // Remove old files.
- return true;
- }
- bool DeleteDiretory(CString strOld)
- {
- //
- // dosn't exist.
- //
- DWORD dwAttr = GetFileAttributes(strOld);
- if (dwAttr == 0xffffffff)
- return true;
- //
- // if file.
- //
- if (dwAttr != 0xffffffff && !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
- {
- if (!DeleteFile (strOld))
- {
- if (GetLastError() == ERROR_ACCESS_DENIED)
- {
- if (!SetFileAttributes(strOld, FILE_ATTRIBUTE_NORMAL))
- return false;
- if (!DeleteFile (strOld))
- return false;
- }
- }
- return true;
- }
- //
- // if directory.
- //
- strOld = formatDir(strOld.GetBuffer(0)).data();
- WIN32_FIND_DATA FileData; // Data structure describes the file found
- BOOL bFinished = FALSE;
- HANDLE hSearch = FindFirstFile (strOld + "*.*", &FileData);
- if (hSearch == INVALID_HANDLE_VALUE)
- return false;
- while (!bFinished)
- {
- CString strOldPath = strOld + FileData.cFileName;
- if (string(FileData.cFileName) != "." &&
- string(FileData.cFileName) != ".." )
- {
- if (!DeleteDiretory(strOldPath))
- {
- FindClose (hSearch);
- return false;
- }
- }
- if (!FindNextFile (hSearch, &FileData))
- bFinished = TRUE;
- }
- // Close the search handle.
- if (!FindClose (hSearch))
- return false;
- if (!RemoveDirectory(strOld))
- return false;
- return true;
- }
- bool SplitPathName(string strFilePath, string& strPath, string& strName)
- {
- // get name map.
- if (strFilePath[strFilePath.size() - 1] == '\')
- strFilePath.erase(strFilePath.size() - 1);
- // copy file to db directory.
- char drive[_MAX_DRIVE];
- char dir[_MAX_DIR];
- char fname[_MAX_FNAME];
- char ext[_MAX_EXT];
- _splitpath(strFilePath.data(), drive, dir, fname, ext);
- if (!strlen(drive) || !strlen(fname))
- return false;
- strPath = drive;
- strPath += dir;
- strName = fname;
- strName += ext;
- return true;
- }
- ///////////////////////////////////////////////////////////////////////////
- // return val : if return string is empty, it is the user cancel select.
- /*
- string SelectFolder()
- {
- string strRet;
- LPMALLOC pMalloc;
- if (::SHGetMalloc(&pMalloc) == NOERROR)
- {
- BROWSEINFO bi;
- char pszBuffer[MAX_PATH];
- LPITEMIDLIST pidl;
- // Get help on BROWSEINFO struct - it's got all the bit settings.
- bi.hwndOwner = AfxGetMainWnd()->GetSafeHwnd();
- bi.pidlRoot = NULL;
- bi.pszDisplayName = pszBuffer;
- bi.lpszTitle = _T("Select a Starting Directory");
- bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; //|BIF_RETURNONLYFSDIRS|BIF_STATUSTEXT; //|BIF_VALIDATE|BIF_EDITBOX;
- bi.lpfn = NULL;
- bi.lParam = 0;
- // This next call issues the dialog box.
- if ((pidl = ::SHBrowseForFolder(&bi)) != NULL)
- {
- if (::SHGetPathFromIDList(pidl, pszBuffer))
- {
- strRet = pszBuffer;
- }
- pMalloc->Free(pidl);
- }
- // Release the shell's allocator.
- pMalloc->Release();
- }
- return strRet;
- }
- //*/
- #define BIF_USENEWUI 0x40
- int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData);
- bool SelectFolder(const CString strDefault, CString &strRet)
- {
- strRet.Empty();
- BROWSEINFO bi;
- TCHAR szDir[MAX_PATH];
- LPITEMIDLIST pidl;
- LPMALLOC pMalloc;
- if (SUCCEEDED(SHGetMalloc(&pMalloc)))
- {
- ZeroMemory(&bi,sizeof(bi));
- bi.hwndOwner = NULL;
- bi.pszDisplayName = 0;
- bi.pidlRoot = 0;
- bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_USENEWUI;
- bi.lpfn = BrowseCallbackProc;
- bi.lParam = (long)(LPCTSTR)strDefault;
- pidl = SHBrowseForFolder(&bi);
- if (pidl)
- {
- if (SHGetPathFromIDList(pidl,szDir))
- {
- strRet = szDir;
- strRet.TrimLeft();
- strRet.TrimRight();
- if (!strRet.IsEmpty())
- {
- if(strRet.GetAt(strRet.GetLength()-1)!='\')
- strRet +="\";
- }
- }
- pMalloc->Free(pidl); pMalloc->Release();
- }
- }
- return strRet.IsEmpty() == 0;
- }
- int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData)
- {
- TCHAR szDir[MAX_PATH];
- switch(uMsg)
- {
- case BFFM_INITIALIZED:
- {
- if (pData)
- {
- SendMessage(hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData);
- }
- else if (GetCurrentDirectory(sizeof(szDir)/sizeof(TCHAR), szDir))
- {
- // WParam is TRUE since you are passing a path.
- // It would be FALSE if you were passing a pidl.
- SendMessage(hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)szDir);
- }
- break;
- }
- case BFFM_SELCHANGED:
- {
- // Set the status window to the currently selected path.
- if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir))
- {
- SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)szDir);
- }
- break;
- }
- default:
- break;
- }
- return 0;
- }
- //////////////////////////////////////////////////////////////////
- //
- // if find return the index. else return -1.
- //
- int binary_search_ex (vector<long> array, int x)
- {
- const int n = array.size();
- int lo = 0, hi = n, mid = 0;
- while(lo != hi)
- {
- mid = lo + (hi - lo) / 2;
- if (x == array[mid])
- return mid;
- if (x < array[mid])
- hi = mid;
- else
- lo = mid + 1;
- }
- return -1;
- }