C++常用操作函數(shù)_第1頁
C++常用操作函數(shù)_第2頁
C++常用操作函數(shù)_第3頁
C++常用操作函數(shù)_第4頁
C++常用操作函數(shù)_第5頁
已閱讀5頁,還剩18頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、C+常用操作函數(shù)載入動(dòng)態(tài)庫bool LoadDll() HttpDownDll = LoadLibrary(HTTPDOWNDLL.dll);if (HttpDownDll = NULL) MessageBox(0,載?入?動(dòng)態(tài)?庫 a錯(cuò)洙?誤6!?,”錯(cuò)洙?誤6, MB_OK|MB_ICONWARNING); FreeLibrary(HttpDownDll); return false ; TOC o 1-5 h z J v y JiISendCommand = (SendCommandFunc)GetProcAddress(HttpDownDll, SendComman。 i- - ;.i

2、f (SendCommand = NULL)-.1MessageBox(0, GetProcAddress 錯(cuò)洙?誤6!?,錯(cuò)洙?誤6, MB_OK|MB_ICONWARNING); FreeLibrary(HttpDownDll);X . X -i Iw- Ireturn false ; return true ;卸載動(dòng)態(tài)庫bool FreeDll()FreeLibrary(HttpDownDll);SendCommand = NULL; return true ;字符串分割std:vector split(std:string str,std:string pattern) std:str

3、ing:size_type pos;std:vector result;str+=pattern; /擴(kuò)?展1字?符?串?以?方?便?操立作痢?int size=str.size();for (int i=0; isize; i+) pos=str.find(pattern,i); if (possize)std:string s=str.substr(i,pos-i);result.push_back(s);i=pos+pattern.size()-1; return result;UTF8 轉(zhuǎn) GBKvoid UTF8ToGBK(std:string &s) char szOut256;m

4、emset(szOut,0,256);strcpy(szOut,s.c_str();unsigned short* wszGbk = NULL;char* szGbk = NULL;/長(zhǎng)度int len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)szOut, -1, NULL, 0);wszGbk = new unsigned shortlen+1;memset(wszGbk, 0, len * 2 + 2);MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)szOut, -1, (LPWSTR)wszGbk, len);

5、/長(zhǎng)度len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGbk, -1, NULL, 0, NULL, NULL);szGbk = new charlen+1;memset(szGbk, 0, len + 1);WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGbk, -1, szGbk, len, NULL, NULL);/ szOut = szGbk; /這樣得到的szOut不正確,因?yàn)榇司湟饬x是將 szGbk的首地址賦給szOut,/當(dāng)delete 口szGbk執(zhí)行后szGbk的內(nèi)存空間將被釋放,此時(shí)將得不

6、到szOut的內(nèi)容memset(szOut,0, strlen(szGbk) + 1); /改將 szGbk 的內(nèi)容賦給 szOut ,這樣即使 szGbk被釋放也能得到正確的值memcpy(szOut, szGbk, strlen(szGbk);s=szOut;delete 口szGbk;delete 口wszGbk;刪除文件int DeleteFileFunc(string v_SourceFile) int l_Result = 0;/* _access(char *,int)判斷文件是否存在存在返回0;不存在返回-1._access(const char *path,int mode)

7、mode的值:00是否存在02寫權(quán)限04讀權(quán)限06讀寫權(quán)限*/char l_SourceFile256 = 0;strcpy(l_SourceFile, v_SourceFile.c_str();if(!_access(l_SourceFile,0)/如果文件存在:文件為只讀無法刪除/去掉文件只讀屬性SetFileAttributes(l_SourceFile,0); if(DeleteFile(l_SourceFile)/刪除成功 l_Result = 0; - 7. 口 else/無法刪除:文件只讀或無權(quán)限執(zhí)行刪除 r 1 l ? r /coutsource 無法刪除:文件為只讀屬性或無刪

8、除權(quán)限.endl; l_Result = 1;return l_Result;string重命名文件int RenameFileFunc(stringv_SourceFile,1 Iv_NewFileName)int l_Result = 0;char l_SourceFile256 = 0;char l_NewFileName256 = 0;strcpy(l_SourceFile, v_SourceFile.c_str();strcpy(l_NewFileName, v_NewFileName.c_str();if(!_access(l_SourceFile, 0)/ 如果文件存在:if(!

9、rename(l_SourceFile, l_NewFileName)刪除成功l_Result = 0;else/無法重命名:文件打開或無權(quán)限執(zhí)行重命名/cout 文件無法重命名(可能原因如下):“endl;coutt1. newname已存在endlJ?p r-./t2. newname 正在使用,未關(guān)閉.endlX , jfi I. I- I / t3. 你沒有權(quán)限重命名此文件.= 6& ovs.dwMinorVersion = 0);/vista or later-F X.X-i Iielse return FALSE;int lang = 0;/char l_Language10 =

10、0;char *l_Language = ReadXmlFile(System, Language, );if(stricmp(l_Language, en) = 0)lang = 1;if(lang = 1)if(bXPLaterOS)SetThreadUILanguage(MAKELANGID(LANG_ENGLISH,SU BLANG_ENGLISH_US);else一7-i廣二SetThreadLocale(MAKELCID(MAKELANGID(LANG_ENGLI SH,SUBLANG_ENGLISH_US),SORT_DEFAULT);X - . jr -I I*w-. If 4

11、.1else if(lang = 0)if(bXPLaterOS)1 ISetThreadUILanguage(MAKELANGID(LANG_CHINESE,S UBLANG_CHINESE_SIMPLIFIED);elseSetThreadLocale(MAKELCID(MAKELANGID(LANG_CHINE SE,SUBLANG_CHINESE_SIMPLIFIED),SORT_DEFAULT);elsereturn FALSE;return TRUE;讀寫xml文件char *ReadXmlFile( char *v_FatherNodeName, char *v_NodeName

12、, char *v_Default)(一一一yj I I z1 I jchar l_ComName20 = 0;char l_TempStr20 = 0;char l_XmlPath256 = 0;char l_ExePath256 = 0;GetModuleFileName(NULL, l_ExePath, 256);int l_ExePathLen = strlen(l_ExePath);for (int i = l_ExePathLen - 1; i = 0; i-) if (l_ExePathi =)memcpy(l_XmlPath, l_ExePath, i); strcat(l_X

13、mlPath, g_XmlFileName);CTinyXMLLib l_TinyXml;strcpy(l_TinyXml.m_XmlPath, l_XmlPath);int l_Result = l_TinyXml.LoadXml();if (l_Result = 0) l_TinyXml.ReadXmlNode(v_FatherNodeName, v_NodeName, v_Default, l_TempStr); else strcpy(l_TempStr, v_Default); return l_TempStr; char *ReadXmlFile( char *v_XmlFileN

14、ame, char *v_FatherNodeName, char *v_NodeName, char *v_Default) char l_XmlPath256 = 0;char l_TempStr20 = 0;char l_ExePath256 = 0;GetModuleFileName(NULL, l_ExePath, 256); int l_ExePathLen = strlen(l_ExePath);for (int i = l_ExePathLen - 1; i = 0; i-) if (l_ExePathi =)memcpy(l_XmlPath, l_ExePath, i); s

15、trcat(l_XmlPath, );strcat(l_XmlPath, v_XmlFileName);CTinyXMLLib l_TinyXml;strcpy(l_TinyXml.m_XmlPath, l_XmlPath);int l_Result = l_TinyXml.LoadXml();if (l_Result = 0) l_TinyXml.ReadXmlNode(v_FatherNodeName, v_NodeName, v_Default, l_TempStr); else strcpy(l_TempStr, v_Default);return l_TempStr;int Writ

16、eXmlFile( char *v_XmlFileName, char *v_FatherNodeName, char *v_NodeName, char *v_Value)char l_ComName20 = 0;char l_XmlPath256 = 0;char l_ExePath256 = 0;GetModuleFileName(NULL, l_ExePath, 256); int l_ExePathLen = strlen(l_ExePath);for (int i = l_ExePathLen - 1; i = 0; i-) if (l_ExePathi =)memcpy(l_Xm

17、lPath, l_ExePath, i); strcat(l_XmlPath, );strcat(l_XmlPath, v_XmlFileName);CTinyXMLLib l_TinyXml;strcpy(l_TinyXml.m_XmlPath, l_XmlPath);l_TinyXml.LoadXml();l_TinyXml.WriteXmlNode(v_FatherNodeName, v_NodeName, v_Value); return 0;讀ini文件int CCommServerDlg:ReadIniFile() char l_TempStr2048 = 0;char l_Cur

18、rentDir256 = 0;l_TempStr, 2048, g_config_name);l_TempStr, 2048, g_config_name);一一一i GetCurrentDirectory(256, l_CurrentDir);strcat(l_CurrentDir, Download);r j l j卞CheckFolderExist(l_CurrentDir);GetPrivateProfileString(Application, LocalFileList, l_FileListPath, l_TempStr, 2048, g_config_name);GetPriv

19、ateProfileString(Application, LocalFileDir, l_LocalFileDir, l_TempStr,2048, g_config_name);return 0;讀文件void Read(char * v_Path, char *v_Buffer, const int v_BufferLen) HANDLE hFile = :CreateFile(v_Path, GENERIC_READ0, NULL, OPEN_EXISTINGNULL, NULL); if (hFile != INVALID_HANDLE_VALUE) /SetFilePointer(

20、hFile, -1, NULL, FILE_END);SetFilePointer(hFile, 81920, NULL, FILE_BEGIN);char l_Buffer5 = 0;DWORD nNumberOfBytesRead;BOOL bRet = :ReadFile(hFile, l_Buffer, v_BufferLen, &nNumberOfBytesRead, NULL); memcpy(v_Buffer, l_Buffer, v_BufferLen);/ TODO .CloseHandle(hFile);void Write(char寫文件v_Path, char *v_C

21、ontent, const intv_ContentSize)HANDLE hFile = :CreateFile(v_Path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);if (hFile != INVALID_HANDLE_VALUE)SetFilePointer(hFile, -1, NULL, FILE_END);Up/ 2,SetFilePointer(hFile, 81920, NULL, FILE_BEGIN);X1門 I-. 、J p I I I j DWORD nNumberOfBytesWritten;二Writ

22、eFile(hFile,v_Content, v_ContentSize,Xy-i I-w- I r. j .&nNumberOfBytesWritten, NULL);/ TODO .CloseHandle(hFile);查找進(jìn)程BOOL FindProcess()int i=0;PROCESSENTRY32 pe32;HANDLEpe32.dwSize = sizeof(pe32);hProcessSnap二:CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);if(hProcessSnap = INVALID_HANDLE_VALUE)i+=0

23、;BOOL bMore = :Process32First(hProcessSnap, &pe32);while(bMore) 一二 r i/Z ,,r I p/printf(進(jìn)程名稱:s n”, pe32.szExeFile);if(stricmp(RWPEPROC.exe,pe32.szExeFile)=0) F. X jr -i I i(/printf(進(jìn)程運(yùn)行中);i+=1;bMore = :Process32Next(hProcessSnap, &pe32);if(i1)大于1 ,排除自身return true;elsereturn false;路徑操作char l_ExePath2

24、56 = 0;char l_MainExePath256 = 0;GetCurrentDirectory(256, l_ExePath);GetModuleFileName(NULL, l_ExePath, 256);int l_ExePathLen = strlen(l_ExePath);for(int i = l_ExePathLen - 1; i = 0; i-)if(l_ExePathi = ) F X J/ |memcpy(l_MainExePath, l_ExePath, i);strcat(l_MainExePath, RWPEPROC.exe);BOOL APIENTRY Dl

25、lMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) switch (ul_reason_for_call) case DLL_PROCESS_ATTACH: char *l_Buffer; l_Buffer = _getcwd(NULL, 0); _getcwd(DllPath, MAXPATH); HMODULE module = GetModuleHandle(G); char szBuffMAX_PATH = 0;GetModuleFileName(module, szBuff, sizeof (sz

26、Buff); int l_Pause = 0;case DLL_THREAD_ATTACH:case DLL_THREAD_DETACH:case DLL_PROCESS_DETACH: break;return TRUE;查找指定進(jìn)程/判斷指定進(jìn)程是否存在% - 1int IsProcExist(char FileName50,bool IsDelete)夕I p !.,char NameBuffMAX_PATH;char *pFileName;/ pFileName 轉(zhuǎn)化為大寫后的字I,一符串指針char *pNameBuff;符串指針BOOL bRes;HINSTANCE hInstan

27、ce;HANDLE hHandle;int i, j; /循環(huán)變量/ NameBuff轉(zhuǎn)化為大寫后的字/ 返回結(jié)果/ 動(dòng)態(tài)庫句柄/ 進(jìn)程句柄int len;funEnumPorcess EnumProcesses;funGetModuleFileNameEx GetModuleFileNameEx;DWORD *buffer, maxNum, factNum;maxNum = MAXPROCESS;factNum = MAXPROCESS;buffer = (DWORD *)malloc(maxNum);hInstance = LoadLibrary(psapi.dll);/ 裝載 psapi

28、.dllif (hInstance)EnumProcesses=x J(funEnumPorcess)GetProcAddress(hInstance,EnumProcesses); n J; nJ pi,111 fif (EnumProcesses)y XI I . f 4.1bRes = EnumProcesses(buffer, maxNum,&factNum);/枚舉進(jìn)程,得到進(jìn)程名稱和實(shí)際進(jìn)程總大小if (bRes)factNum /= sizeof(DWORD); / 計(jì)算實(shí)際進(jìn)程個(gè)數(shù)GetModuleFileNameEx=(funGetModuleFileNameEx)GetPr

29、ocAddress(hInstance, GetModuleFileNameExA);if (GetModuleFileNameEx)for (i=0; i= l_ProcNums)HANDLEhHandleOpenProcess(PROCESS_ALL_ACCESS,FALSE,pe32.th32ProcessID); / 獲取進(jìn)程句柄TerminateProcess(hHandle,0);CloseHandle(hHandle);bMore = :Process32Next(hProcessSnap, &pe32);if(i=1)/大于1 ,排除自身return true;n /VW pl

30、,1 relsereturn false; 一二、T,/| 二.J)寫日志,刪除日志/目錄是否存在的檢查,不存在建立:bool CheckFolderExist(char *v_StrPath) WIN32_FIND_DATA l_Wfd;bool l_Result = false;HANDLE hFind = FindFirstFile(v_StrPath, &l_Wfd);if (hFind != INVALID_HANDLE_VALUE) & (l_Wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)l_Result = true;)elseif(

31、CreateDirectory(v_StrPath, NULL) l_Result = false;FindClose(hFind);return l_Result;/遍歷目錄中所有的文件BOOL DirectoryList(char *v_Path)WIN32_FIND_DATA l_WFindData;HANDLE hFind;char l_FilePathName128=0;/構(gòu)造路徑char l_FullPathName128=0;bool l_SearchFinished=false;strcpy(l_FilePathName, v_Path);strcat(l_FilePathNa

32、me, *);hFind = FindFirstFile(l_FilePathName, &l_WFindData);if (hFind = INVALID_HANDLE_VALUE)/printf(搜索失敗!);return 0;while(二FindNextFile(hFind, &l_WFindData)sprintf(l_FullPathName, %s%s, v_Path, l_WFindData.cFileName); DeleteFile(l_FullPathName);FindClose(hFind);二RemoveDirectory(v_Path);return 0;int

33、DeleteLogDir()int l_Result=0;time_t t=time(0);for(int i = 5; i = 13; i+)time_t l_DeleteDate = t - i*24*60*60;/三天前%y%m%dServiceLogs,char l_DeleteDirName64 = 0;strftime(l_DeleteDirName,sizeof(l_DeleteDirName),localtime(&l_DeleteDate);char l_DeleteDirPath256 = 0;strcpy(l_DeleteDirPath, logpath);strcat(

34、l_DeleteDirPath, Logs);strcat(l_DeleteDirPath, l_DeleteDirName);DirectoryList(l_DeleteDirPath);return l_Result;bool LocalWriteLog(char * v_FileName , char * v_Module , const char * v_LogInfo) time_t t = time(0);char l_FileName64 = 0;char l_DirName256 = 0;strcpy(l_DirName, logpath);strcat(l_DirName,

35、Logs);char l_Temp3;CheckFolderExist(l_DirName);char l_DirYMD32 = 0;strftime(l_DirYMD, sizeof(l_DirYMD), %y%m%dServiceLogs, localtime(&t);strcat(l_DirName, );1r i strcat(l_DirName, l_DirYMD);CheckFolderExist(l_DirName);/strftime( l_FileName, sizeof(l_FileName), %Y-%m-%d-,localtime(&t);strcat(l_FileNa

36、me , v_FileName);if(v_FileName != NULL | v_Module != NULL | v_LogInfo != NULL)fstream l_FileHandle;strcat(l_DirName, );strcat(l_DirName, l_FileName);l_FileHandle.open(l_DirName ,ios:app);if(!l_FileHandle)char l_Buffer50 = 0;memcpy(l_Buffer , l_FileName , strlen(l_FileName);memcpy(l_Buffer + strlen(l

37、_FileName) , Open Log Error , 20);/MessageBox(NULL , l_Buffer , error , MB_OK);time_t t = time(0);char tmp64;strftime( tmp, sizeof(tmp), %d %X,localtime(&t);l_FileHandle TIME : tmpMODULE | v_Module v_LogInfoendl;l_FileHandle.close();return true;return false;啟動(dòng)程序(以system權(quán)限啟動(dòng)顯示界面)/for win7DWORD _stdca

38、ll LaunchAppIntoDifferentSession( LPTSTR lpCommand )DWORD dwRet = 0;PROCESS_INFORMATION pi ;STARTUPINFO si ;DWORD dwSessionld ;HANDLE hUserToken = NULL;HANDLE hUserTokenDup = NULL;HANDLE hPToken = NULL;HANDLE hProcess = NULL;DWORD dwCreationFlags ;HMODULE hInstKernel32 = NULL;typedef DWORD (WINAPI *

39、 WTSGetActiveConsoleSessionIdPROC)();WTSGetActiveConsoleSessionldPROC WTSGetActiveConsoleSessionld = NULL;hInstKernel32 = LoadLibrary (Kernel32.dll);if (!hInstKernel32)1/一?一.:.I I t.return FALSE ; I- i I .,iOutputDebugString(LaunchAppIntoDifferentSession 1n);WTSGetActiveConsoleSessionld=(WTSGetActiv

40、eConsoleSessionldPROC )GetProcAddress( hInstKernel32,WTSGetActiveConsoleSe ssionld);/ Log the client on to the local computer. dwSessionld = WTSGetActiveConsoleSessionld (); do WTSQueryUserToken( dwSessionld ,&hUserToken );dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;ZeroMemory( &si

41、, sizeof( STARTUPINFO );si.cb = sizeof( STARTUPINFO );pDesktop = winsta0default;ZeroMemory( &pi , sizeof( pi);TOKEN_PRIVILEGES tp ;LUID luid ;if(!:OpenProcessToken ( GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGE STOKEN_QUERY| TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_SESSIONID| TOKEN_READ |

42、 TOKEN_WRITE , &hPToken ) dwRet = GetLastError ();break; else;if ( !LookupPrivilegeValue ( NULL, SE_DEBUG_NAME, &luid ) dwRet = GetLastError (); break; else;tp.PrivilegeCount =1;tp.Privileges 0.Luid = luid;tp.Privileges 0.Attributes = SE_PRIVILEGE_ENABLED;if(!DuplicateTokenEx ( hPToken, MAXIMUM_ALLO

43、WED, NULLSecurityIdentification , TokenPrimary, & hUserTokenDup )dwRet = GetLastError (); break;else;,.一 一1 ; - , /Adjust Token privilege if(!SetTokenInformation ( hUserTokenDup,TokenSessionId ,(void*)&dwSessionId,sizeof (DWORD) dwRet = GetLastError (); break; else;if(!AdjustTokenPrivileges ( hUserT

44、okenDup, FALSE, &tpsizeof(TOKEN_PRIVILEGES ), (PTOKEN_PRIVILEGES) NULL, NULL )dwRet = GetLastError (); break; else;LPVOID pEnv =NULL;if( CreateEnvironmentBlock ( &pEnv, hUserTokenDup, TRUE ) dwCreationFlags|=CREATE_UNICODE_ENVIRONMENT ; else pEnv =NULL;/ Launch the process in the clients logon sessi

45、on.if( CreateProcessAsUser ( hUserTokenDup, / clients access token NULL, / file to execute lpCommand, / command line NULL, / pointer to process SECURITY_ATTRIBUTES NULL, / pointer to thread SECURITY_ATTRIBUTES FALSE, / handles are not inheritable dwCreationFlags,/ creation flags pEnv, / pointer to n

46、ew environment blockNULL, / name of current directory& si,/ pointer to STARTUPINFO structure& pi/ receives information about new process)elsedwRet = GetLastError ();break;while( 0 );/Perform All the Close Handles task,.一 一 if( NULL != hUserToken ) CloseHandle( hUserToken );else;if( NULL != hUserToke

47、nDup)CloseHandle( hUserTokenDup );else;if( NULL != hPToken )CloseHandle( hPToken );else;return dwRet ;建立取消磁盤映射連接int_stdcallCreateConn(char *v_LocalName, char *v_RemoteName, char *v_PSW, char*v_UserName, char *v_ReturnBuffer)int l_Result = 0;trychar l_ReturnBuffer256 = 0;DWORD dwRetVal;NETRESOURCE nr;DWORD dwFlags;memset(&nr, 0, sizeof (NETRESOURCE);nr.dwType =

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論