Thursday, February 8, 2007
Unicode使用123
記得碩一的時候為了處理中文路徑就已經survey過了
但是年代久遠又忘光了,這次就做個筆記吧!
(from Windows System Programming 3th)
Windows NT之後內部的系統都是用unicode在作處理(豆知識)
NTFS的file name與file path都是unicode編碼
在Windows 底下如果要寫可以同時處理Unicode(UTF-16)與ASCII(8-bits)字串的程式,
以下有 幾條guideline可以follow:
1.使用TCHAR、LPTSTR以及LPCTSTR
我們來看一下TCHAR的定義:
#ifdef UNICODE
#define TCHAR WCHAR
#else
#define TCHAR CHAR
#endif
很棒吧!
LPTSTR則是:
#ifdef UNICODE
typedef LPWSTR LPTSTR;
#else
typedef LPSTR LPTSTR;
#endif
LPCTSTR:
#ifdef UNICODE
typedef LPCWSTR LPCTSTR;
#else
typedef LPCSTR LPCTSTR;
#endif
簡單的說,上面的三個type會依照程式的define,在Unicode或ASCII之間變換
2.如果要使用Unicode,在所有的module中定義#define UNICODE
以及 #define _UNICODE。前者控制windows function,後者控制C library。
這兩個定義要下在windows.h之前。如果要處理的是ASCII的話,就不需要define。
3.用sizeof(TCHAR)幫你計算buffer size
4.使用tchar.h中的general C library function,如:
_fgettc, _itot (for itoa), _stprintf (for sprintf), _tstcpy (for strcpy), _ttoi,
_totupper, _totlower,_tprintf.
"_"代表的意義是這些function由Microsoft C所提供,這些function在其他的系統上
應該是以不同的名字出現。
5.include tchar.h after windows.h,to get required definitions for text macros and
generic C library functions
6.用下面的格式表示constant string:
L"this is string"
_T("this is string")
前者由ANSI C所提供,後者由Microsoft C compiler所支援。
書中還有提到幾個好玩的事情
1.String comparisons can use lstrcmp and lstrcmpi rather than the generic _tcscmp and _tcscmpi to account for the specific language and region, or locale, at run time and also to perform word rather than string comparisons.String comparisons simply compare the numerical values of the characters, whereas word comparisons consider locale-specific word order.
有意思,下次來用看看會得到怎樣的結果。
2.程式的entry point可以用_tmain來取代,會依照定義變成main或wmain。
#include
#include
int _tmain (int argc, LPTSTR argv [])
{
...
}
這樣就可以吃ASCII或Unicode的命令列引數了
3.有一些程式會依照define在底層做變形,例如CreateFile,當定義Unicode時會呼叫
CreateFileW,不然就會呼叫CreateFileA。在Debug資訊裡面就會看到這些我們沒有呼叫的
function。(奇怪,我明明呼叫的是CreateFile,怎麼有CreateFileA??)
Labels:
Programming
Subscribe to:
Post Comments (Atom)
1 comment:
那中文的 literal 要怎麼寫?像是 _T("我是中文字"); 嗎?
不過 Visual Studio 系列的 IDE 好像都是預設用 ISO-8859-1 或 Big5 在存檔耶...這樣有辦法處理難搞的中文字嗎?
Post a Comment