FormatMessage で可変個の引数の順序を入れ替える関数

#include <windows.h>
#include <string>
#include <cstdio>
#include <cstdlib>

bool sprintf2(std::string& buf, const char* fmt, ...);

int main()
{

	const char* a1 = "(1)";
	const char* a2 = "(2)";
	const char* a3 = "(3)";

	std::string buf;
	if (!sprintf2(buf, "%3 %2 %1", a1, a2, a3)){

		EXIT_FAILURE;
	}
	buf += "\r\n";

	printf(buf.c_str());
	getchar();

	return EXIT_SUCCESS;
}

bool sprintf2(std::string& buf, const char* fmt, ...)
{

	LPVOID lpMsgBuf = NULL;

	va_list marker;
	va_start(marker, fmt); // 可変個の引数の初期化

	if (0 == ::FormatMessage(
	    FORMAT_MESSAGE_ALLOCATE_BUFFER |
	    FORMAT_MESSAGE_FROM_STRING,
	    (LPCVOID)fmt, 0,
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
	    (LPTSTR)&lpMsgBuf, 0, &marker)){

		va_end(marker); // 可変個の引数のリセット
		if (NULL != lpMsgBuf){

			LocalFree(lpMsgBuf);
			lpMsgBuf = NULL;
		}
		return false;
	}

	va_end(marker); // 可変個の引数のリセット

	buf = (const char*)lpMsgBuf;

	if (NULL != lpMsgBuf){

		LocalFree(lpMsgBuf);
		lpMsgBuf = NULL;
	}

	return true;
}

BACK


View My Stats