Source

sdl2pal / src / util.c

Full commit
#include "util.h"

/*
	Purpose:
		Does a varargs printf into a temp buffer, so we don't need to have
		varargs versions of all text functions.

	Parameters:
		[IN] format - the format string.

	Return value:
		Pointer to the result string.
*/
char *va(const char *format, ...)
{
	static char string[256];
	va_list argptr;

	va_start(argptr, format);
	vsnprintf(string, 256, format, argptr);
	va_end(argptr);

	return string;
}

/*
	Purpose:
		Terminate the game as an error occurs and prints the
		error message provided.

	Parameters:
		[IN] format - error message.

	Return value:
		None.
*/
void TerminateOnError(const char *format, ...)
{
	va_list argptr;
	char s[256];
	extern void PAL_Shutdown(void);

	va_start(argptr, format);
	vsnprintf(s, sizeof(s), format, argptr);
	va_end(argptr);

	fprintf(stderr, "\nFATA ERROR: %s\n", s);

#if defined(WIN32)
	MessageBoxA(NULL, s, "FATAL ERROR", MB_ICONERROR);
#endif

#if defined(__linux__)
	system(va("beep; xmessage -center \"FATAL ERROR: %s\"", s));
#endif

#if defined(_DEBUG)
	assert(0 || "TerminateOnError()");	// allows jumping to debugger
#endif

	PAL_Shutdown();
	exit(255);
}

/*
	Purpose:
		sleep for a while.

	Parameters:
		[IN] ms - ms to sleep.

	Return value:
		None.
*/
void UTIL_Delay(unsigned int ms)
{
	unsigned int t = SDL_GetTicks() + ms;

	while (SDL_PollEvent(NULL));

	while (SDL_GetTicks() < t)
	{
		SDL_Delay(1);
		while (SDL_PollEvent(NULL));
	}
}

/*
	Purpose:
		Open a required file. If fails, quit the program.

	Parameters:
		[IN] fileName - file name to open.

	Return value:
		Pointer to the file.
*/
FILE* UTIL_OpenRequiredFile(const char *fileName)
{
	FILE *fp;
	fp = fopen(va("%s%s", PAL_PREFIX, fileName), "rb");
	if (fp == NULL)
	{
		TerminateOnError("File not found: %s!\n", fileName);
	}
	return fp;
}

/*
	Purpose:
		Close a file.

	Parameters:
		[IN] fp - file handle to be closed.

	Return value:
		None.
*/
void UTIL_CloseFile(FILE *fp)
{
	if (fp != NULL)
	{
		fclose(fp);
	}
}