c++

vsprintf の使用例

MessageBox を printf 形式の書式が使えるようにする例。デバッグなどに役立つ。

#include <windows.h>
#include <tchar.h>

static const char MessageBoxTitle[] = "AppTitle";
void MessageBoxf(char *format, ...);

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance
	, LPTSTR lpCmdLine, int nCmdShow)
{
	MessageBoxf("%s(%d)", __FILE__, __LINE__);
}

void MessageBoxf(char *format, ...)
{
	char buf[1024+1];
	va_list args;
	va_start(args, format);
#ifdef _MSC_VER
	vsprintf_s(buf, sizeof(buf), format, args);	// Microsoft Visual C
#else
	wvsprintf(buf, format, args);	// WIN32 API
//	vsprintf(buf, format, args);	// C Runtime Function
#endif

	MessageBox(NULL, buf, MessageBoxTitle,
		MB_ICONEXCLAMATION | MB_APPLMODAL | MB_OK | MB_SETFOREGROUND);

	va_end(args);
}
注意:
上記コード中に出てくる ... (点点点) も、その通り記述すること。
決してホームページ掲載のために省略しているのでは無いデス。

vsprintf と同等の機能を持つものに、いくつか種類があるので適宜つかい分けるといい。
vsprintf標準Cランタイム版。ほとんどのCコンパイラで使える。
wvsprintfWIN32 API版。1024 バイトを超える結果は切り捨てられます。
vsprintf_s最近の Microsoft Visual C版。バッファ オーバーフロー対策してあります。
wvsprintf_sそんなのありません。