#define STRICT
long min(long a, long b)
{
long c;
c = (a < b)?(a):(b);
return c;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define DEFAULT_BUFF_LEN 512
int Utf8ToUtf16(wchar_t *dest, size_t dest_size, char *src, size_t src_size);
int main(int argc, char *argv[])
{
char instr[DEFAULT_BUFF_LEN];
wchar_t outstr[DEFAULT_BUFF_LEN];
wchar_t bom;
char outbuffbom[4];
FILE *pFile;
long sizeFile;
size_t countRead;
int iResult = 0;
int instr_size = 0;
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;
memset(outstr, 0, sizeof(outstr));
iResult = Utf8ToUtf16(outstr, sizeof(outstr), instr, instr_size);
if (iResult == FALSE)
{
perror("Utf8ToUtf16() Failed.\n");
return 1;
}
printf("%d 文字変換しました。\n", iResult);
pFile = fopen("out.txt", "wb");
if (pFile == NULL)
{
perror("ファイルが開けません: out.txt");
return 1;
}
bom = 0xfeff;
memcpy(outbuffbom, &bom, sizeof(wchar_t));
fwrite(outbuffbom, sizeof(wchar_t), 1, pFile);
fwrite(outstr, iResult * 2, 1, pFile);
fclose(pFile);
}
int Utf8ToUtf16(wchar_t *dest, size_t dest_size, char *src, size_t src_size)
{
/**/
UINT uCodePage;
DWORD dwFlags;
LPCSTR lpMultiByteStr;
int cchMultiByte;
LPWSTR lpWideCharStr;
int cchWideChar;
int iResult = 0;
uCodePage = CP_UTF8;
dwFlags = 0;
lpMultiByteStr = src;
cchMultiByte = src_size;
lpWideCharStr = dest;
cchWideChar = dest_size;
iResult = MultiByteToWideChar(uCodePage, dwFlags, lpMultiByteStr
, cchMultiByte, lpWideCharStr, cchWideChar);
return iResult;
}
|