C++ 工具类 [StrUtil] 和 工具方法

#pragma once

#ifndef STRUTIL_H
#define STRUTIL_H

#include <string>
#include <vector>
#include <sstream>
#include <Windows.h>

using namespace std;

static const string tag = "[DaTiBao] ";

namespace StrUtil
{
	inline std::wstring AnsiToUnicode(const char* buf);
	inline std::string AnsiToUtf8(const char* buf);
	inline std::string UnicodeToAnsi(const wchar_t* buf);
	inline std::wstring Utf8ToUnicode(const char* buf);
	inline std::string UnicodeToUtf8(const wchar_t* buf);
	inline std::string TrimLeft(const std::string& str);
	inline std::string TrimRight(const std::string& str);
	inline std::string Trim(const std::string& str);
	inline std::vector<std::string> Split(std::string& str, const char* c);
	inline std::string GetModulePath();
	inline void Replace(std::string&srcstr,const std::string&oldstr,const std::string&newstr);
	inline HMODULE GetCurrentModule();
	inline void DebugString(std::string);
};

namespace StrUtil {
	void Replace(std::string&srcstr,const std::string&oldstr,const std::string&newstr)  
	{  
		string::size_type pos=0;  
		string::size_type a=oldstr.size();  
		string::size_type b=newstr.size();  
		while((pos=srcstr.find(oldstr,pos))!=string::npos)  
		{  
			srcstr.replace(pos,a,newstr);  
			pos+=b;  
		}  
	} 

	std::vector<std::string> Split(std::string& str, const char* c)
	{
		char *cstr, *p;
		std::vector<std::string> res;
		cstr = new char[str.size() + 1];
		strcpy(cstr, str.c_str());
		p = strtok(cstr, c);
		while (p != NULL)
		{
			res.push_back(p);
			p = strtok(NULL, c);
		}
		return res;
	}

	std::wstring AnsiToUnicode(const char* buf)
	{
		int len = ::MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
		if (len == 0) return L"";
		std::vector<wchar_t> unicode(len);
		::MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);
		return &unicode[0];
	}

	std::string AnsiToUtf8( const char* buf )
	{
		return UnicodeToUtf8(AnsiToUnicode(buf).c_str());
	}

	std::string UnicodeToAnsi(const wchar_t* buf)
	{
		int len = ::WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);
		if (len == 0) return "";
		std::vector<char> utf8(len);
		::WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, NULL, NULL);
		return &utf8[0];
	}

	std::wstring Utf8ToUnicode(const char* buf)
	{
		int len = ::MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0);
		if (len == 0) return L"";
		std::vector<wchar_t> unicode(len);
		::MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len);
		return &unicode[0];
	}

	std::string UnicodeToUtf8(const wchar_t* buf)
	{
		int len = ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
		if (len == 0) return "";
		std::vector<char> utf8(len);
		::WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);
		return &utf8[0];
	}

	std::string TrimLeft(const std::string& str) {
		std::string t = str;
		for (std::string::iterator i = t.begin(); i != t.end(); i++) {
			if (!isspace(*i)) {
				t.erase(t.begin(), i);
				break;
			}
		}
		return t;
	}

	std::string TrimRight(const std::string& str) {
		if (str.begin() == str.end()) {
			return str;
		}
		std::string t = str;
		for (std::string::iterator i = t.end() - 1; i != t.begin(); i--) {
			if (!isspace(*i)) {
				t.erase(i + 1, t.end());
				break;
			}
		}
		return t;
	}

	std::string Trim(const std::string& str) {
		std::string t = str;

		std::string::iterator i;
		for (i = t.begin(); i != t.end(); i++) {
			if (!isspace(*i)) {
				t.erase(t.begin(), i);
				break;
			}
		}
		if (i == t.end()) {
			return t;
		}

		for (i = t.end() - 1; i != t.begin(); i--) {
			if (!isspace(*i)) {
				t.erase(i + 1, t.end());
				break;
			}
		}
		return t;
	}

	HMODULE GetCurrentModule()
	{ // NB: XP+ solution!
		HMODULE hModule = NULL;
		GetModuleHandleEx(
			GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
			(LPCTSTR)GetCurrentModule,
			&hModule);

		return hModule;
	}

	std::string GetModulePath()
	{
		char fullPath[MAX_PATH];
		char drive[_MAX_DRIVE];
		char dir[_MAX_DIR];
		HMODULE hModule = GetCurrentModule();
		if(0 == GetModuleFileNameA(hModule, fullPath, MAX_PATH))
			return "";

		_splitpath(fullPath, drive, dir, NULL, NULL);
		std::string str = std::string(drive) + dir;
		return str;
	}

	void DebugString(std::string msg) {
		vector<string> msgSplit = Split(msg,"\n");
		for(int i=0; i<msgSplit.size(); i++) {
			std::ostringstream oss;
			oss << tag << msgSplit[i] << endl;
			OutputDebugStringA(oss.str().c_str());
		}
	}
}

#endif


int RunCmd(string cmdStr) {
	ostringstream wss;

	STARTUPINFO si = { sizeof(si) };
	PROCESS_INFORMATION pi;
	si.dwFlags = STARTF_USESHOWWINDOW; // 指定wShowWindow成员有效
	si.wShowWindow = SW_SHOWNORMAL; //窗口最大化
	//si.wShowWindow = SW_SHOWNORMAL; 
	BOOL bRet = ::CreateProcess (
		NULL,
		const_cast<char *>(cmdStr.c_str()),//命令行参数
		//NULL,
		NULL,// 默认进程安全性
		NULL,// 默认进程安全性
		FALSE,// 指定当前进程内句柄不可以被子进程继承
		NORMAL_PRIORITY_CLASS,// 为新进程创建一个新的控制台窗口
		NULL,// 使用本进程的环境变量
		NULL,// 使用本进程的驱动器和目录
		&si,
		&pi);
	if(bRet)
	{
		// 不使用的句柄最好关掉
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
		//新进程的ID号:pi.dwProcessId
		//新进程的主线程ID号:pi.dwThreadId

		wss << cmdStr << "  :  execute succeed";
		DebugString(wss.str());
		return 0;
	}

	wss << cmdStr << "  :  execute fail,GetLastError()=" << GetLastError();
	DebugString(wss.str());

	return -1;
}

BOOL KillProcessByName(LPCSTR lpProcessName)
{
	DebugString(lpProcessName);
	//创建进程快照(TH32CS_SNAPPROCESS表示创建所有进程的快照)
	HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);

	//PROCESSENTRY32进程快照的结构体
	PROCESSENTRY32 pe;

	//实例化后使用Process32First获取第一个快照的进程前必做的初始化操作
	pe.dwSize = sizeof(PROCESSENTRY32);


	//下面的IF效果同:
	//if(hProcessSnap == INVALID_HANDLE_VALUE)   无效的句柄
	if(!Process32First(hSnapShot,&pe))
	{
		return FALSE;
	}
	CString strProcessName = lpProcessName;

	//将字符串转换为小写
	strProcessName.MakeLower();


	//如果句柄有效  则一直获取下一个句柄循环下去
	while (Process32Next(hSnapShot,&pe))
	{

		//pe.szExeFile获取当前进程的可执行文件名称
		CString scTmp = pe.szExeFile;


		//将可执行文件名称所有英文字母修改为小写
		scTmp.MakeLower();

		//比较当前进程的可执行文件名称和传递进来的文件名称是否相同
		//相同的话Compare返回0
		if(!scTmp.Compare(strProcessName))
		{

			//从快照进程中获取该进程的PID(即任务管理器中的PID)
			DWORD dwProcessID = pe.th32ProcessID;
			HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE,FALSE,dwProcessID);
			::TerminateProcess(hProcess,0);
			CloseHandle(hProcess);
			return TRUE;
		}
		scTmp.ReleaseBuffer();
	}
	strProcessName.ReleaseBuffer();
	return FALSE;
}


你可能感兴趣的:(C++ 工具类 [StrUtil] 和 工具方法)