例 4-1 は、あるファイルに対して複数バイト・ワイド文字の相互変換 API を適用するプログラム例です。これらの API を使用する場合は、適切なヘッダーファイルを取り込む必要があります。たとえば mbtowc()、mbstowcs()、wctomb()、wcstombs()、mblen() を使用する場合は stdlib.h を取り込み、ungetwc()、fgetws()、fputwc()、fputws() を使用する場合は wchar.h を取り込みます。さらに、処理の最初の段階で setlocale() を呼び出し、動作ロケールを適切に設定する必要があります。
sun% cat my_mbwc.c /* * Read lines from stdin and * count the number of chars * that belong to specific category. * Counting will stop if input reaches * EOF. It is assumed that each line * has at most BUFSIZ - 1 byte length. * * To categorize each chars, iswctype() * is used. Therefore, it is necessary * to convert the input multibyte buffer * to the wide char buffer. mbstowcs() * is called for that purpose. */ #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <wchar.h> static char mbbuf[BUFSIZ]; static wchar_t wcbuf[BUFSIZ]; int main(int argc, char *argv[]) { size_t retval; int i, alpha_char, ideo_char, kana_char, other_char; setlocale(LC_ALL, ""); alpha_char = ideo_char = kana_char = other_char = 0; while(fgets(mbbuf, BUFSIZ, stdin) != NULL) { retval = mbstowcs(wcbuf, mbbuf, BUFSIZ); if (retval == (size_t)-1) { fprintf(stderr, "Invalid char is found during mbstowcs()¥n"); exit(-1); } retval = wcslen((const wchar_t *)wcbuf); for (i = 0; i < retval; i++) { if (iswctype(wcbuf[i], wctype("jisx0201r"))) { kana_char++; } else if (iswctype(wcbuf[i], wctype("jkanji"))) { ideo_char++; } else if (iswctype(wcbuf[i], wctype("alpha"))) { alpha_char++; } else { other_char++; } } } fprintf(stdout, "The input consist of¥n"); fprintf(stdout, "%d Alphabetical chars,¥n", alpha_char); fprintf(stdout, "%d JIS X 0208/0212 Kanji chars,¥n", ideo_char); fprintf(stdout, "%d JIS X 0201 Kana chars and¥n", kana_char); fprintf(stdout, "%d other chars.¥n", other_char); return(0); } sun% cc -o my_mbwc my_mbwc.c sun% cat file6 /* Here's the content of file3 */ 新しいシステム*は現在のネットワーク*環境を変えることなく インターネット*とのシームレス*な接続を可能にします。また セキュリティ*の問題も新しい認証テクノロジー*を用いることで アドミニストレータ*の負担を減らしています。 /* Here's the content of file5 */ ひらがなはかたかなに置換されます。 カタカナハヒラガナニ置換サレマス。 漢字、記号、全角alphabetや JIS X 0201 カナナドハ* 置換 サレマセン*。 sun% ./my_mbwc < file6 The input consist of 54 Alphabetical chars, 31 JIS X 0208/0212 Kanji chars, 56 JIS X 0201 Kana chars and 117 other chars.
* の部分のカタカナは、半角カタカナになります。