#define STRICT
#include <stdio.h>
#include "utf16_to_cp932_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 512
int Utf16ToCp932(char *dest, size_t dest_size, wchar_t *src, size_t src_size);
int main(int argc, char *argv[])
{
wchar_t instr[DEFAULT_BUFF_LEN];
char outstr[DEFAULT_BUFF_LEN];
FILE *pFile;
long sizeFile = 0;
size_t countRead;
int instr_size = 0;
int iResult = 0;
char *pOutStr = NULL;
wchar_t *pInStr = NULL;
memset(instr, 0, sizeof(instr));
pFile = fopen("data.txt", "rb");
if (pFile == NULL)
{
perror("ファイルがひらけません: data.txt");
return 1;
}
fseek(pFile, 0, SEEK_END);
sizeFile = ftell(pFile);
fseek(pFile, 0, SEEK_SET);
countRead = fread(instr, min(sizeFile, DEFAULT_BUFF_LEN), 1, pFile);
fclose(pFile);
if (countRead == 0)
{
perror("ファイル読み込み失敗: data.txt");
return 1;
}
instr_size = min(sizeFile, DEFAULT_BUFF_LEN) * countRead / sizeof(wchar_t);
pInStr = instr;
if (*pInStr == 0xfeff)
{
pInStr++;
instr_size--;
}
memset(outstr, 0, sizeof(outstr));
iResult = Utf16ToCp932(outstr, sizeof(outstr), pInStr, instr_size);
if (iResult == FALSE)
{
perror("Utf16ToCp932() Failed.\n");
return 1;
}
printf("%d バイト変換しました。\n", iResult);
pOutStr = outstr;
pFile = fopen("out.txt", "wb");
if (pFile == NULL)
{
perror("ファイルが開けません: out.txt");
return 1;
}
fwrite(pOutStr, iResult, 1, pFile);
fclose(pFile);
return 0;
}
int Utf16ToCp932(char *dest, size_t dest_size, wchar_t *src, size_t src_size)
{
long countNeedsBytes;
long cursor;
wchar_t unicode;
unsigned int cp932code;
long sizeBytes;
const char dummy_code = 0x3f;
if (dest_size == 0)
{
}
else
{
if (dest == NULL)
{
return FALSE;
}
if (dest_size < 0)
{
return FALSE;
}
}
if (src == NULL)
{
return FALSE;
}
if (src_size < 0)
{
return FALSE;
}
countNeedsBytes = 0;
for (cursor = 0; cursor < src_size; cursor++)
{
unicode = *(src + cursor);
cp932code = utf16_to_cp932_table[unicode];
if (cp932code <= 0x00ff)
{
sizeBytes = 1;
}
else
{
sizeBytes = 2;
}
if (dest_size && (dest_size < (countNeedsBytes + sizeBytes)))
{
return countNeedsBytes;
}
if (dest_size)
{
if (cp932code == 0x0000)
{
if (unicode == 0x0000)
{
*(dest) = (char)0x00;
dest++;
}
else
{
*(dest) = (char)dummy_code;
dest++;
}
}
else if (sizeBytes == 1)
{
*(dest) = (char)((cp932code) & 0x00ff);
dest++;
}
else
{
*(dest) = (char)((cp932code >> 8) & 0x00ff);
dest++;
*(dest) = (char)((cp932code) & 0x00ff);
dest++;
}
}
countNeedsBytes += sizeBytes;
}
return countNeedsBytes;
}
|