わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

Unicode(BOM付き)のiniファイルを作成する

iniファイルは、読み出し/書き込みの際に、iniファイルの文字コードがUnicodeなら 読み出し/書き込みもユニコードして処理され、それ以外ならSHIFT-JISコードとして処理されます。

Unicodeで処理をさせたい場合には、BOM付きのiniファイルを用意することで、 Unicodeでiniファイルの読み書きを行うことができます。

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>



/*
	Unicode(BOM付き)のiniファイルを作成する
*/
int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	/*
		std::wcoutのロケールを設定
		 これを設定するだけで、std::wcoutで日本語が表示される
		 ようになります。
	*/
	std::wcout.imbue( std::locale( "", std::locale::ctype ) );

	// iniファイルパス
	std::wstring strInfilePath = L".¥¥TestUnicode.ini";


	/*
		Unicode(BOM付き)のiniファイルを作成する
	*/
	{
		std::ofstream oIniFile( strInfilePath.c_str(), std::ios::binary );
		if ( !oIniFile.is_open() ) {
			std::wcout << L"ファイルの作成に失敗しました。" << std::endl;
		}
		else {

			// BOMの書き込み(Unicodeにする為)
			oIniFile.write( (const char*)"¥xff¥xfe", 2 );
			if( oIniFile.fail() ) { 
				std::wcout << L"BOMの書き込みに失敗しました。" << std::endl;
			}

			// ファイルのクローズ
			oIniFile.close();
		}
	}


	/*
		iniファイル書き込み
	*/
	if ( 0 == ::WritePrivateProfileString( L"SECTION", L"key", L"テスト文字列", strInfilePath.c_str() ) ) {

		std::wcout << L"iniファイルへの書き込みに失敗しました。" << std::endl;
	}
	else {

		std::wcout << L"iniファイルへ書き込みました。" << std::endl;
	}

	// 正常終了
	return( 0 );
}



実行結果

iniファイルへ書き込みました。






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。