C++ツールクラス[StrUtil]とツールメソッド

6754 ワード

#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,"
"); 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;
}