C常用操作函数.pdf

上传人:ylj18****70940 文档编号:72369097 上传时间:2023-02-10 格式:PDF 页数:50 大小:836.30KB
返回 下载 相关 举报
C常用操作函数.pdf_第1页
第1页 / 共50页
C常用操作函数.pdf_第2页
第2页 / 共50页
点击查看更多>>
资源描述

《C常用操作函数.pdf》由会员分享,可在线阅读,更多相关《C常用操作函数.pdf(50页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、C 常用操作函数 The document was prepared on January 2,2021C+常用操作函数载入动态库bool LoadDll()HttpDownDll=LoadLibrary(HTTPDOWNDLL.dll);if(HttpDownDll=NULL)MessageBox(0,载入动态库 a 错洙误!,错洙?误,MB_OK|MB_ICONWARNING);FreeLibrary(HttpDownDll);return false;SendCommand=(SendCommandFunc)GetProcAddress(HttpDownDll,SendCommand);

2、if(SendCommand=NULL)MessageBox(0,GetProcAddress 错洙?误!,错洙?误,MB_OK|MB_ICONWARNING);FreeLibrary(HttpDownDll);return false;return true;卸载动态库bool FreeDll()FreeLibrary(HttpDownDll);SendCommand=NULL;return true;字符串分割std:vector split(std:string str,std:string pattern)std:string:size_type pos;std:vector resu

3、lt;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;memset(szOut,0,256);strcpy(szOut,s.c_str();unsigne

4、d 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);/长度len=WideCharToMultiByte(CP_ACP,0,(LPWSTR)wszGbk,-1,NULL,0,NULL,NULL);szG

5、bk=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 的内存空间将被释放,此时将得不到 szOut 的memset(szOut,0,strlen(szGbk)+1);/改将 szGbk 的内容赋给 szOut,这样即使 szGbk 被释放也能得到正确的值memcpy(

6、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)mode 的值:00 是否存在02 写权限04 读权限06 读写权限*/char l_SourceFile256=0;strcpy(l_SourceFile,v_SourceFile.c_str();if(

7、!_access(l_SourceFile,0)/如果文件存在:文件为只读无法删除/去掉文件只读属性SetFileAttributes(l_SourceFile,0);if(DeleteFile(l_SourceFile)/删除成功l_Result=0;else/无法删除:文件只读或无权限执行删除/coutsource 无法删除:文件为只读属性或无删除权限.endl;l_Result=1;return l_Result;重命名文件int RenameFileFunc(string v_SourceFile,string v_NewFileName)int l_Result=0;char l_S

8、ourceFile256=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(!rename(l_SourceFile,l_NewFileName)/删除成功l_Result=0;else/无法重命名:文件打开或无权限执行重命名/cout文件无法重命名(可能原因如下):endl;/coutt1.newname 已存在endl/t2.newname 正在使

9、用,未关闭.endl/t3.你没有权限重命名此文件.=6&ovs.dwMinorVersion=0);/vista or laterelsereturn FALSE;int lang=0;/char l_Language10=0;char*l_Language=ReadXmlFile(System,Language,);if(stricmp(l_Language,en)=0)lang=1;if(lang=1)if(bXPLaterOS)SetThreadUILanguage(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US);elseSetThreadLoc

10、ale(MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT);else if(lang=0)if(bXPLaterOS)SetThreadUILanguage(MAKELANGID(LANG_CHINESE,SUBLANG_CHINESE_SIMPLIFIED);elseSetThreadLocale(MAKELCID(MAKELANGID(LANG_CHINESE,SUBLANG_CHINESE_SIMPLIFIED),SORT_DEFAULT);elsereturn FALSE;return TRUE;读写 x

11、ml 文件char*ReadXmlFile(char*v_FatherNodeName,char*v_NodeName,char 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-)char*v_Default)if(l_ExePathi=)memcpy(l_XmlPath,l_ExePath,

12、i);strcat(l_XmlPath,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);elsestrcpy(l_TempStr,v_Default);return l_TempStr;char*ReadXmlFile(char*v_XmlFileName,ch

13、ar*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);strcat(l_XmlPath,);strcat(l_XmlPath,v_Xm

14、lFileName);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);elsestrcpy(l_TempStr,v_Default);return l_TempStr;int WriteXmlFile(char*v_XmlFileName,char*v_FatherNodeName,char

15、*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_XmlPath,l_ExePath,i);strcat(l_XmlPath,);strcat(l_XmlPath,v_XmlFileName);CTinyXMLLib l_T

16、inyXml;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_CurrentDir256=0;GetPrivateProfileString(Application,RemoteFileListURL,http:/172.18.1.170:9131/Down

17、load/FileList.txt,l_TempStr,2048,g_config_name);GetPrivateProfileString(Application,RemoteDirURL,http:/172.18.1.170:9131/Download/,l_TempStr,2048,g_config_name);GetCurrentDirectory(256,l_CurrentDir);strcat(l_CurrentDir,Download);CheckFolderExist(l_CurrentDir);GetPrivateProfileString(Application,Loca

18、lFileList,l_FileListPath,l_TempStr,2048,g_config_name);GetPrivateProfileString(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_READ,0,NULL,OPEN_EXISTING,NULL,NULL);if(h

19、File!=INVALID_HANDLE_VALUE)/SetFilePointer(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 Wri

20、te(char*v_Path,char*v_Content,const int v_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);SetFilePointer(hFile,81920,NULL,FILE_BEGIN);DWORD nNumberOfBytesWritten;:WriteFile(hFile,v_Conten

21、t,v_ContentSize,&nNumberOfBytesWritten,NULL);/TODO.CloseHandle(hFile);查找进程BOOL FindProcess()int i=0;PROCESSENTRY32 pe32;pe32.dwSize=sizeof(pe32);HANDLE hProcessSnap=:CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);if(hProcessSnap=INVALID_HANDLE_VALUE)i+=0;BOOL bMore=:Process32First(hProcessSnap,&pe32

22、);while(bMore)/printf(进程名称:%s n,pe32.szExeFile);if(stricmp(RWPEPROC.exe,pe32.szExeFile)=0)/printf(进程运行中);i+=1;bMore=:Process32Next(hProcessSnap,&pe32);if(i1)/大于 1,排除自身return true;elsereturn false;路径操作char l_ExePath256=0;char l_MainExePath256=0;/GetCurrentDirectory(256,l_ExePath);GetModuleFileName(NU

23、LL,l_ExePath,256);int l_ExePathLen=strlen(l_ExePath);for(int i=l_ExePathLen-1;i=0;i-)if(l_ExePathi=)memcpy(l_MainExePath,l_ExePath,i);strcat(l_MainExePath,RWPEPROC.exe);BOOL APIENTRY DllMain(HMODULE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)switch(ul_reason_for_call)case DLL_PROCESS_ATTACH:

24、char*l_Buffer;l_Buffer=_getcwd(NULL,0);_getcwd(DllPath,MAXPATH);HMODULE module=GetModuleHandle(0);char szBuffMAX_PATH=0;GetModuleFileName(module,szBuff,sizeof(szBuff);int l_Pause=0;case DLL_THREAD_ATTACH:case DLL_THREAD_DETACH:case DLL_PROCESS_DETACH:break;return TRUE;查找指定进程/判断指定进程是否存在int IsProcExis

25、t(char FileName50,bool IsDelete)char NameBuffMAX_PATH;char*pFileName;/pFileName 转化为大写后的字符串指针 char*pNameBuff;/NameBuff 转化为大写后的字符串指针 BOOL bRes;/返回结果 HINSTANCE hInstance;/动态库句柄 HANDLE hHandle;/进程句柄 int i,j;/循环变量 int len;funEnumPorcess EnumProcesses;funGetModuleFileNameEx GetModuleFileNameEx;DWORD*buffe

26、r,maxNum,factNum;maxNum=MAXPROCESS;factNum=MAXPROCESS;buffer=(DWORD*)malloc(maxNum);hInstance=LoadLibrary(psapi.dll);/装载 psapi.dll if(hInstance)EnumProcesses=(funEnumPorcess)GetProcAddress(hInstance,EnumProcesses);if(EnumProcesses)bRes=EnumProcesses(buffer,maxNum,&factNum);/枚举进程,得到进程名称和实际进程总大小 if(bR

27、es)factNum/=sizeof(DWORD);/计算实际进程个数 GetModuleFileNameEx=(funGetModuleFileNameEx)GetProcAddress(hInstance,GetModuleFileNameExA);if(GetModuleFileNameEx)for(i=0;i=l_ProcNums)HANDLE hHandle=OpenProcess(PROCESS_ALL_ACCESS,FALSE,pe32.th32ProcessID);/获取进程句柄TerminateProcess(hHandle,0);CloseHandle(hHandle);b

28、More=:Process32Next(hProcessSnap,&pe32);if(i=1)/大于 1,排除自身return true;elsereturn false;写日志,删除日志/目录是否存在的检查,不存在建立: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_ATTR

29、IBUTE_DIRECTORY)l_Result=true;elseif(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_FilePathN

30、ame,v_Path);strcat(l_FilePathName,*.*);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(

31、v_Path);return 0;int 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;/三天前char l_DeleteDirName64=0;strftime(l_DeleteDirName,sizeof(l_DeleteDirName),%y%m%dServiceLogs,localtime(&l_DeleteDate);char l_DeleteDirPath256=0;strcpy(l_DeleteDirPath,logpath);s

32、trcat(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,Logs);char l_Te

33、mp3;CheckFolderExist(l_DirName);char l_DirYMD32=0;strftime(l_DirYMD,sizeof(l_DirYMD),%y%m%dServiceLogs,localtime(&t);strcat(l_DirName,);strcat(l_DirName,l_DirYMD);CheckFolderExist(l_DirName);/strftime(l_FileName,sizeof(l_FileName),%Y-%m-%d-,localtime(&t);strcat(l_FileName,v_FileName);if(v_FileName!=

34、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);20);memcpy(l_Buffer+strlen(l_FileName),Open Log Error,/MessageBox(NULL,l_Buff

35、er,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 _stdcall LaunchAppIntoDifferentSession(LPTSTR lpCommand)DWORD dwRet=0;PROCESS

36、_INFORMATION pi;STARTUPINFO si;DWORD dwSessionId;HANDLE hUserToken=NULL;HANDLE hUserTokenDup=NULL;HANDLE hPToken=NULL;HANDLE hProcess=NULL;DWORD dwCreationFlags;HMODULE hInstKernel32 =NULL;typedef DWORD(WINAPI*WTSGetActiveConsoleSessionIdPROC)();WTSGetActiveConsoleSessionIdPROC WTSGetActiveConsoleSe

37、ssionId=NULL;hInstKernel32=LoadLibrary(Kernel32.dll);if(!hInstKernel32)return FALSE;OutputDebugString(LaunchAppIntoDifferentSession 1n);WTSGetActiveConsoleSessionId=(WTSGetActiveConsoleSessionIdPROC)GetProcAddress(hInstKernel32,WTSGetActiveConsoleSessionId);/Log the client on to the local computer.d

38、wSessionId=WTSGetActiveConsoleSessionId();do WTSQueryUserToken(dwSessionId,&hUserToken);dwCreationFlags=NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE;ZeroMemory(&si,sizeof(STARTUPINFO);si.cb=sizeof(STARTUPINFO);si.lpDesktop=winsta0default;ZeroMemory(&pi,sizeof(pi);TOKEN_PRIVILEGES tp;LUID luid;if(!:OpenP

39、rocessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID|TOKEN_READ|TOKEN_WRITE,&hPToken)dwRet=GetLastError();break;else;if(!LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&luid)dwRet=GetLastError();break;else;tp.PrivilegeCount=1;tp.Pri

40、vileges 0.Luid=luid;tp.Privileges 0.Attributes=SE_PRIVILEGE_ENABLED;if(!DuplicateTokenEx(hPToken,MAXIMUM_ALLOWED,NULL,SecurityIdentification,TokenPrimary,&hUserTokenDup)dwRet=GetLastError();break;else;/Adjust Token privilege if(!SetTokenInformation(hUserTokenDup,TokenSessionId,(void*)&dwSessionId,si

41、zeof(DWORD)dwRet=GetLastError();break;else;if(!AdjustTokenPrivileges(hUserTokenDup,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL,NULL)dwRet=GetLastError();break;else;LPVOID pEnv=NULL;if(CreateEnvironmentBlock(&pEnv,hUserTokenDup,TRUE)dwCreationFlags|=CREATE_UNICODE_ENVIRONMENT;else pEnv

42、=NULL;/Launch the process in the clients logon session.if(CreateProcessAsUser(hUserTokenDup,/clients accesstoken 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,/

43、creation flags pEnv,/pointer to new environment block NULL,/name of current directory&si,/pointer to STARTUPINFO structure&pi /receives information about new process )else dwRet=GetLastError();break;while(0);/Perform All the Close Handles task if(NULL!=hUserToken)CloseHandle(hUserToken);else;if(NULL

44、!=hUserTokenDup)CloseHandle(hUserTokenDup);else;if(NULL!=hPToken)CloseHandle(hPToken);else;return dwRet;建立取消磁盘映射连接int _stdcall CreateConn(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 d

45、wFlags;memset(&nr,0,sizeof(NETRESOURCE);nr.dwType=RESOURCETYPE_ANY;nr.lpLocalName=v_LocalName;/nr.lpRemoteName=LYLTESTShareFile;nr.lpRemoteName=v_RemoteName;nr.lpProvider=NULL;dwFlags=CONNECT_UPDATE_PROFILE;dwRetVal=WNetAddConnection2(&nr,v_PSW,v_UserName,dwFlags);if(dwRetVal=NO_ERROR)l_ReturnBuffer

46、);elsel_ReturnBuffer);l_Result=0;strcpy(l_ReturnBuffer,Success);LocalWriteLog(LOG_RUNFILE,CreateConn|WNetAddConnection2,/printf(Connection added to%sn,nr.lpRemoteName);l_Result=-1;GetLastErrMsg(l_ReturnBuffer);LocalWriteLog(LOG_ERRFILE,CreateConn|WNetAddConnection2,strcpy(v_ReturnBuffer,l_ReturnBuff

47、er);catch(exception ex)l_Result=-2;strcpy(v_ReturnBuffer,ex.what();return l_Result;int _stdcall CancelConn(char*v_LocalName,char*v_ReturnBuffer)int l_Result=0;trychar l_ReturnBuffer256=0;DWORD dwResult;/Call the WNetCancelConnection2 function,specifying/that the connection should no longer be a pers

48、istent one./dwResult=WNetCancelConnection2(v_LocalName,CONNECT_UPDATE_PROFILE,/remove connection from profileFALSE);/fail if open files or jobs/Process errors./The device is not a local redirected device./if(dwResult=NO_ERROR)l_Result=0;strcpy(l_ReturnBuffer,Success);LocalWriteLog(LOG_RUNFILE,CancelConn|WNetAddConnection2,l_ReturnBuffer);elsel_Result=-1;GetLastErrMsg(l_ReturnBuffer);LocalWriteLog(LOG_ERRFILE,CancelConn|WNetAddConnection2,l_ReturnBuffer);strcpy(v_ReturnBuffer,l_ReturnBuffer);catch(exception ex)l_Result=-2;strcpy(v_ReturnBuffer,ex.what();return l_Result;

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 应用文书 > 工作报告

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁