在windows環境中用vs2015編譯程序後,函數GetModuleFileName獲取到的路徑使用printf打印出來只有磁盤符,而不是整個路徑。vs2015編譯時設置的字符集是unicode,(其中:Unicode通常用兩個字節表示一個字符,這是與ASCII編碼不同的地方,網上很多資料有描述)我遇到問題是,用GetModuleFileName獲取到路徑後,還想保存到char型的字符數組中,網上關於怎麼打印出來有很多資料,但是很少有簡單解釋怎麼保存的,下面附上我的打印和保存的代碼段。
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <atlstr.h>
using namespace std;
string UnicodeToUtf8(const wstring& wstr) {
// 預算-緩衝區中多字節的長度
int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
// 給指向緩衝區的指針變量分配內存
char *pAssii = (char*)malloc(sizeof(char)*ansiiLen);
// 開始向緩衝區轉換字節
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);
string ret_str = pAssii;
free(pAssii);
return ret_str;
}
char* UnicodeToAnsi(const wchar_t* szStr)
{
int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL);
if (nLen == 0)
{
return NULL;
}
char* pResult = new char[nLen];
WideCharToMultiByte(CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL);
return pResult;
}
string UnicodeToAnsi_str(const wchar_t* szStr)
{
int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL);
if (nLen == 0)
{
return NULL;
}
char* pResult = new char[nLen];
WideCharToMultiByte(CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL);
string str(pResult);
delete(pResult);
return str;
}
int main()
{
TCHAR buffer[MAX_PATH]; // MAX_PATH 默認宏
char *buf;
int len = GetModuleFileName(NULL, buffer, MAX_PATH);
printf("初始獲取路徑:[%d]\n", len); // 不可用 ascii 來輸出 unicode 的字符串,不然無法得到結果
wprintf(L"[%ls]\n", buffer);
printf("[%s]\n", buffer);
buf = UnicodeToAnsi(buffer);
std::wcout << buffer << std::endl;
printf("轉爲Ansi數組後 [%s]\n", buf);
string str(buf, len);
delete(buf);
int dwfind = str.find_last_of("\\");
string strpath = str.substr(0, dwfind);
string strname = str.substr(dwfind + 1);
printf(" [%s] [%d]\n [%s]\n [%s]\n", str.c_str(), dwfind, strpath.c_str(), strname.c_str());
std::string strpath_1 = UnicodeToAnsi_str(buffer);
printf("轉爲Ansi字符串後[%s]\n", strpath_1.c_str());
system("pause");
return 0;
}
執行輸出如下圖: