#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define DEFAULT_BUFF_LEN 512
int Utf16ToUtf8(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;
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);
memset(outstr, 0, sizeof(outstr));
iResult = Utf16ToUtf8(outstr, sizeof(outstr), instr, instr_size);
if (iResult == FALSE)
{
perror("Utf16ToUtf8() Failed.\n");
return 1;
}
printf("%d バイト変換しました。\n", iResult);
pOutStr = outstr;
if ((*pOutStr == '\xef') && (*(pOutStr + 1) == '\xbb')
&& (*(pOutStr + 2) == '\xbf'))
{
pOutStr += 3;
iResult -= 3;
}
pFile = fopen("out.txt", "wb");
if (pFile == NULL)
{
perror("ファイルが開けません: out.txt");
return 1;
}
fwrite(pOutStr, iResult, 1, pFile);
fclose(pFile);
return 0;
}
int Utf16ToUtf8(char *dest, size_t dest_size, wchar_t *src, size_t src_size)
{
UINT uCodePage;
DWORD dwFlags;
LPCWSTR lpWideCharStr;
int cchWideChar;
LPSTR lpMultiByteStr;
int cchMultiByte;
LPCSTR lpDefaultChar;
LPBOOL lpfUsedDefaultChar;
int iResult;
uCodePage = CP_UTF8;
dwFlags = 0;
lpWideCharStr = src;
cchWideChar = src_size;
lpMultiByteStr = dest;
cchMultiByte = dest_size;
lpDefaultChar = NULL;
lpfUsedDefaultChar = NULL;
iResult = WideCharToMultiByte(uCodePage, dwFlags, lpWideCharStr
, cchWideChar, lpMultiByteStr, cchMultiByte, lpDefaultChar
, lpfUsedDefaultChar);
return iResult;
}
|