Linux 底下,針對 Unicode 有另外一套 lib calls,
定義在 wchar.h 中. wchar_t 定義的字元,就是 16-bit 的
unicode 碼.
unicode constant string 可以用 L"string" 的方式定義.
利用 mbstowcs(wchar_t *, const char*, size_t) (定義在 stdlib.h)
可以把一般的字串,轉成 wchar_t 的 unicode 字串,
所有 wchar 有關的 lib calls 都只收 wchar 的字串,
包括檔名,目錄名,還有 wprintf()中的 format 字串.
wprintf 中需要印出 wchar 字串的話, 要用 %ls, 而不是 %s.
利用 _wopendir(), _wreaddir(), _wclosedir() 可以得到
目錄中所有檔名,目錄名的 unicode 名稱.
但是直接用 wprintf() 印 unicode 字串, stdout 沒辦法正確
印出 16-bit unicode.
Windows DOS prompt 底下可以用 chcp 更改 code page,
但是只有支援 utf-8 的 code page, 沒有支援 utf-16 unicode
的 code page,所以目前用 wprintf 沒有辦法在任何 console
直接印出 unicode, 只能把 wchar 輸出到檔案,再用可以
顯示 unicode 的 file reader 閱讀.
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
wchar_t filename[80];
char output_name[] = "dir.txt";
main(int argc, char *argv[])
{
_WDIR *wdir;
struct _wdirent *wdirptr;
FILE *outf;
if (argc<2)
{
printf("usage : %s PATHNAME\n", argv[0]);
printf(" This program needs a parameter of dir path name\n");
return(-1);
}
mbstowcs(filename, argv[1], strlen(argv[1]));
wdir = _wopendir(filename);
outf = fopen(output_name,"wb");
while ((wdirptr = _wreaddir(wdir)) != NULL)
{
wprintf(L"FILE : %d %ls\n", wdirptr->d_namlen, wdirptr->d_name);
fputws(wdirptr->d_name, outf);
}
_wclosedir(wdir);
fclose(outf);
return(0);
}
沒有留言:
張貼留言