C++常用操作函数_第1页
C++常用操作函数_第2页
C++常用操作函数_第3页
C++常用操作函数_第4页
C++常用操作函数_第5页
已阅读5页,还剩18页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、C+常用操作函数载入动态库bool LoadDll() HttpDownDll = LoadLibrary(HTTPDOWNDLL.dll);if (HttpDownDll = NULL) MessageBox(0,载?入?动态?库 a错洙?误6!?,”错洙?误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 错洙?误6!?,错洙?误6, MB_OK|MB_ICONWARNING); FreeLibrary(HttpDownDll);X . X -i Iw- Ireturn false ; return true ;卸载动态库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; /扩?展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 转 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;/长度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、/长度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不正确,因为此句意义是将 szGbk的首地址赋给szOut,/当delete 口szGbk执行后szGbk的内存空间将被释放,此时将得不

6、到szOut的内容memset(szOut,0, strlen(szGbk) + 1); /改将 szGbk 的内容赋给 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写权限04读权限06读写权限*/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/无法删除:文件只读或无权限执行删除 r 1 l ? r /coutsource 无法删除:文件为只读属性或无删

8、除权限.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/无法重命名:文件打开或无权限执行重命名/cout 文件无法重命名(可能原因如下):“endl;coutt1. newname已存在endlJ?p r-./t2. newname 正在使用,未关闭.endlX , jfi I. I- I / t3. 你没有权限重命名此文件.= 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);查找进程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(进程名称:s n”, pe32.szExeFile);if(stricmp(RWPEPROC.exe,pe32.szExeFile)=0) F. X jr -i I i(/printf(进程运行中);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;查找指定进程/判断指定进程是否存在% - 1int IsProcExist(char FileName50,bool IsDelete)夕I p !.,char NameBuffMAX_PATH;char *pFileName;/ pFileName 转化为大写后的字I,一符串指针char *pNameBuff;符串指针BOOL bRes;HINSTANCE hInstan

27、ce;HANDLE hHandle;int i, j; /循环变量/ NameBuff转化为大写后的字/ 返回结果/ 动态库句柄/ 进程句柄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);/枚举进程,得到进程名称和实际进程总大小if (bRes)factNum /= sizeof(DWORD); / 计算实际进程个数GetModuleFileNameEx=(funGetModuleFileNameEx)GetPr

29、ocAddress(hInstance, GetModuleFileNameExA);if (GetModuleFileNameEx)for (i=0; i= l_ProcNums)HANDLEhHandleOpenProcess(PROCESS_ALL_ACCESS,FALSE,pe32.th32ProcessID); / 获取进程句柄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;/构造路径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;启动程序(以system权限启动显示界面)/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等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论