Win32コンソールアプリケーションとして実行。
Win32コンソールのプロジェクトに設定したこと
- 空のプロジェクト作成
- プロジェクトのプロパティ
- リンカー
- システム
- サブシステムを「コンソール」に指定。
- プロジェクトのプロパティ
- 全般の文字セットで「Unicode文字セットを使用する」に指定。
次のコードを実行すると、UTF-16のテキストファイルができる。
#include <windows.h>
#include <tchar.h>
#include <local.h>
int _tmain()
{
// 変数宣言。
HANDLE hFile = NULL;
TCHAR tcFF = TEXT("\xFF");
TCHAR tcFE = TEXT("\xFE");
DWORD dwByteWritten = 0;
TCHAR *temp;
TCHAR tcTemp[MAX_PATH];
DWORD dwByteRead = 0;
// ロケール指定(Unicodeを使う時に必要)
_tsetlocale(LC_ALL, TEXT("ja"));
_tprintf(TEXT("aiueo\n"));
_tprintf(TEXT("あいうえお\n"));
_tprintf(TEXT("sizeof(tchar) = %d\n"), sizeof(TCHAR));
// ファイル作成。
hFile = CreateFile(
TEXT("d:/visualstduio/test/test.ini"), GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL
);
if (hFile == INVALID_HANDLE_VALUE || hFile == NUL) {
_tprintf(TEXT("hFile = NULL\n"));
system("pause");
exit(0);
}
// BOMをファイルに書き込む。
if (WriteFile(hFile, &tcFF, 1, &dwByteWritten, NULL) == 0) {
_tprintf(TEXT("書き込みエラー(\xFF)\n");
system("pause");
exit(0);
}
_tprintf(TEXT("tcFF dwByteWritten = %d\n"), dwByteWritten);
if (WriteFile(hFile, &tcFE, 1, &dwByteWritten, NULL) == 0) {
_tprintf(TEXT("書き込みエラー(\xFE)\n");
system("pause");
exit(0);
}
// 文字列をファイルに書き込む。
// TCHAR * 文字列長とやらないと末尾にゴミ(多分終端文字)が入る。
temp = TEXT("あいうえお");
if (WriteFile(hFile, temp, sizeof(TCHAR) * lstrlen(temp), &dwByteWritten, NULL) == 0) {
_tprintf(TEXT("書き込みエラー(あいうえお)\n");
system("pause");
exit(0);
}
// ファイルから文字列を読み込む。
// 読み込む位置をファイルの最初にして、そこからBOMをスキップする。
SetFilePointer(hFile, 2, NULL, FILE_BEGIN);
// 文字列を読み込んで表示する。
if (ReadFile(hFile, tcTemp, sizeof(tcTemp), &dwByteRead, NULL) == 0) {
_tprintf(TEXT("読み込みエラー\n"));
system("pause");
exit(0);
}
_tprintf(TEXT("lstrlen(tcTemp) = %d\n"), lstrlen(tcTemp));
_tprintf(TEXT("読み込み:%s\n"), tcTemp);
// 終了処理。
CloseHandle(hFile);
system("pause");
return 0;
}