常用代码杂记
输出中文
locale loc( "chs" ); wcout.imbue( loc ); wcout << GetExePath().GetBuffer() << endl;
编码转换
#pragma once #include <windows.h> #include <atlstr.h> #include <string> typedef std::basic_string<TCHAR, std::char_traits<TCHAR>,std::allocator<TCHAR> > tstring; std::string t2a(CString input) { USES_CONVERSION; return T2A(input); } std::string t2a(tstring input) { USES_CONVERSION; return T2A(input.c_str()); } CString a2t(std::string input) { USES_CONVERSION; return A2T(input.c_str()); } tstring a2t_2(std::string input) { USES_CONVERSION; return A2T(input.c_str()); } char* UnicodeToUtf8(const wchar_t* unicode) { int len; len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, NULL, 0, NULL, NULL); char *szUtf8 = (char*)malloc(len + 1); memset(szUtf8, 0, len + 1); WideCharToMultiByte(CP_UTF8, 0, unicode, -1, szUtf8, len, NULL, NULL); return szUtf8; } CString UTF82WCS(const char* szU8) { //预转换,得到所需空间的大小; int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), NULL, 0); //分配空间要给'\0'留个空间,MultiByteToWideChar不会给'\0'空间 wchar_t* wszString = new wchar_t[wcsLen + 1]; //转换 ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), wszString, wcsLen); //最后加上'\0' wszString[wcsLen] = '\0'; CString unicodeString(wszString); delete[] wszString; wszString = NULL; return unicodeString; }
读取文件
#pragma once #include <fstream> #include <sstream> #include <string> std::string GetFileContents(std::string filename) { std::ifstream ifs(filename.c_str()); if (ifs.good()) { std::stringstream ss; ss << ifs.rdbuf(); return ss.str(); } return ""; } std::string GetFileContents2(std::string filename) { std::ifstream ifs(filename.c_str()); if (ifs.good()) { std::string strBuffer((std::istreambuf_iterator<char>(ifs)),std::istreambuf_iterator<char>()); return strBuffer; } return ""; }
获取文件路径
#pragma once #include <atlstr.h> // 获取当前可执行文件的路径 CString GetExePath() { CString strCurPath; GetModuleFileName(NULL, strCurPath.GetBuffer(MAX_PATH), MAX_PATH); strCurPath.ReleaseBuffer(); return strCurPath.Left(strCurPath.ReverseFind(_T('\\'))); } // 获取当前可执行文件的文件名 CString GetExeName() { CString strCurPath; GetModuleFileName(NULL, strCurPath.GetBuffer(MAX_PATH), MAX_PATH); strCurPath.ReleaseBuffer(); return strCurPath.Mid(strCurPath.ReverseFind(_T('\\'))+1); }