CP932 to UTF-16 example
更新日2007年02月02日

CP932 to UTF-16 example
CP932 to UTF-16 への文字コード変換のサンプル実装。
MinGW + gcc 環境において動作確認してあります。

Example Code
以下の例は、Cp932ToUtf16()の実装の例です。 [cp932_to_utf16_c.zip]
/*
 * file:Cp932ToUtf16.c
 */
#define STRICT
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cp932_to_utf16_table.c"
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef min
#define min(a,b) ((a)<(b)?(a):(b))
#endif
#define DEFAULT_BUFF_LEN 2048

int Cp932ToUtf16(wchar_t *dest, size_t dest_size, char *src, size_t src_size);

int main(int argc, char *argv[])
{
    char        inpStr[DEFAULT_BUFF_LEN + 1];
    wchar_t     outStr[DEFAULT_BUFF_LEN + 1];
    FILE        *pInpFile;
    FILE        *pOutFile;
    long        sizeInpFile;
    size_t      countRead;
    size_t      sizeRead;
    int         iResult = 0;
    wchar_t     bom;
    
    /*
     * ファイルより文字列を読み込み
     */
    memset(inpStr, 0, sizeof(inpStr));
    pInpFile = fopen("data.txt", "rb");
    if (pInpFile == NULL)
    {
        perror("ファイルが開けません: data.txt");
        return 1;
    }
    fseek(pInpFile, 0, SEEK_END);
    sizeInpFile = ftell(pInpFile);
    fseek(pInpFile, 0, SEEK_SET);
    countRead = fread(inpStr, min(sizeInpFile, DEFAULT_BUFF_LEN), 1, pInpFile);
    fclose(pInpFile);
    if (!countRead)
    {
        perror("ファイル読み込み失敗: data.txt");
        return 1;
    }
    
    sizeRead = min(sizeInpFile, DEFAULT_BUFF_LEN) * countRead;
    
    /*
     * cp932:inpStr -> utf16:outStr 変換。
     */
    memset(outStr, 0, sizeof(outStr));
    iResult = Cp932ToUtf16(outStr, DEFAULT_BUFF_LEN, inpStr, sizeRead);
    if (iResult == FALSE)
    {
        fprintf(stderr, "Cp932ToUtf16() Failed.\n");
        return 1;
    }
    printf("%d 文字変換しました。\n", iResult);
    
    /*
     * ファイルに文字列を書き込み。
     */
    pOutFile = fopen("out.txt", "wb");
    if (pOutFile == NULL)
    {
        perror("ファイルが開けません: out.txt");
        return 1;
    }
    bom = 0xfeff;
    fwrite((char *)&bom, sizeof(wchar_t), 1, pOutFile);
    fwrite(outStr, iResult * sizeof(wchar_t), 1, pOutFile);
    fclose(pOutFile);
    
    return 0;
}

/**
 * 文字コードをCP932よりUTF-16へと変換。
 * 
 * @param[out] dest 出力文字列UTF-16
 * @param[in]  dest_size destの文字数
 * @param[in]  src 入力文字列CP932
 * @param[in]  src_size 入力文字列のバイト数
 * 
 * @return 成功時には出力文字列の文字数を戻します。
 *         dest_size に0を指定し、こちらの関数を呼び出すと、変換された
 *         文字列を格納するのに必要なdestの文字数を戻します。
 *         関数が失敗した場合には、FALSEを戻します。
 */
int Cp932ToUtf16(wchar_t *dest, size_t dest_size, char *src, size_t src_size)
{
    const int       nMaxReadSize            = 2;
    int             countNeedsWords         = 0;
    int             cursor                  = 0;
    int             nReadDataSize           = 0;
    unsigned char   chBuffer[nMaxReadSize];
    unsigned char   ch1                     = 0;
    unsigned char   ch2                     = 0;
    int             sizeBytes               = 0;
    wchar_t         wcWork                  = 0;
    int             iWork1                  = 0;
    int             iWork2                  = 0;
    int             iWork3                  = 0;
    
    /*
     * 入力パラメータをチェック
     */
    if (dest_size)
    {
        /* dest_size != 0 */
        if (dest == NULL)
        {
            /* Error -- Null Pointer Exception : dest */
            return FALSE;
        }
        if (dest_size < 0)
        {
            /* Error -- dest_size < 0 */
            return FALSE;
        }
    }
    if (src == NULL)
    {
        /* Error -- Null Pointer Exception : src */
        return FALSE;
    }
    if (src_size < 1)
    {
        /* Error -- src_size < 1 */
        return FALSE;
    }
    
    countNeedsWords = 0;
    for (cursor = 0; cursor < src_size;)
    {
        /* src より2バイトのデータを読み出し */
        nReadDataSize = (nMaxReadSize < (src_size - cursor))?(nMaxReadSize):(src_size - cursor);
        memcpy(chBuffer, (src + cursor), nReadDataSize);
        memset(chBuffer + nReadDataSize, 0, sizeof(chBuffer) - nReadDataSize);
        
        ch1 = *chBuffer;
        ch2 = *(chBuffer + 1);
        /* data size の調べる */
        if (   (ch1 <= 0x7f)
            || (0xa1 <= ch1 && ch1 <= 0xdf))
        {
            /*
             * <制御コード>0x00~0x1f, 0x7f</制御コード>
             * <ASCII文字>0x20~0x7e</ASCII文字>
             * <半角カタカナ>0xa1~0xdf</半角カタカナ>
             */
            sizeBytes = 1;
        }
        else if (      (   (0x81 <= ch1 && ch1 <= 0x9f)
                        || (0xe0 <= ch1 && ch1 <= 0xfc)
                       )
                    && (   (0x40 <= ch2 && ch2 <= 0x7e)
                        || (0x80 <= ch2 && ch2 <= 0xfc)
                       )
                )
        {
            /*
             * <漢字>
             *     0x8140~0x9ffc, 0xe040~0xfcfc
             *     (第1バイト:0x81~0x9f, 0xe0~0xfc)
             *     (第2バイト:0x40~0x7e, 0x80~0xfc)
             * </漢字>
             */
            sizeBytes = 2;
        }
        else
        {
            /* error(ここに出現してはいけないコード) */
            return FALSE;
        }
        
        /*
         * dest_size をチェック
         */
        if (dest_size && (dest_size < (countNeedsWords + 1)))
        {
            /* Error : memory is not enough for dest */
            return countNeedsWords;
        }
        
        /* sizeBytes毎に処理を分岐 */
        if (dest_size) switch (sizeBytes)
        {
        case 1:
            /*
             * <制御コード>0x00~0x1f, 0x7f</制御コード>
             * <ASCII文字>0x20~0x7e</ASCII文字>
             * <半角カタカナ>0xa1~0xdf</半角カタカナ>
             */
            wcWork = cp932_to_utf16_table[ch1];
            if (ch1 != 0x00 && wcWork == 0x0000)
            {
                wcWork = 0xff1f;    /* ダミーデータ */
            }
            *dest = wcWork;
            dest++;
            break;
        case 2:
            /*
             * <漢字>
             *     0x8140~0x9ffc, 0xe040~0xfcfc
             *     (第1バイト:0x81~0x9f, 0xe0~0xfc)
             *     (第2バイト:0x40~0x7e, 0x80~0xfc)
             * </漢字>
             */
            iWork1 = (int)ch1;
            iWork1 <<= 8;
            iWork1 &= 0xff00;
            iWork2 = (int)ch2;
            iWork2 &= 0x00ff;
            iWork3 = iWork1 | iWork2;
            wcWork = cp932_to_utf16_table[iWork3];
            if (wcWork == 0x0000)
            {
                wcWork = 0xff1f;    /* ダミーデータ */
            }
            *dest = wcWork;
            dest++;
            break;
        default:
            break;
        }
        countNeedsWords++;
        cursor += sizeBytes;
    }
    
    return countNeedsWords;
}