#include <io.h>
#include <stdio.h>
#include <windows.h>
void perrorWin32();

int main() {
	char buf[1];
	HANDLE hStdin;
	DWORD mode;
	DWORD got;

	// Setting terminal to raw mode...
	hStdin = GetStdHandle(STD_INPUT_HANDLE);

	if (GetFileType(hStdin) == FILE_TYPE_CHAR) {
		GetConsoleMode(hStdin, &mode);
		if (
			!SetConsoleMode(
				hStdin,
				mode & ~(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT))
		) {
			perrorWin32();
			return 1;
		}
	}

	// Using a POSIX API

	got = read(0, buf, 1);
	if (got < 0)
		perror(NULL);
	else if (got == 0)
		printf("Got nothing\n");
	else
		printf("'%c' %d\n", buf[0], buf[0]);

	// Using the Windows API

	if (!ReadFile(hStdin, buf, 1, &got, NULL))
		perrorWin32();
	else if (got < 1)
		printf("Got nothing\n");
	else
		printf("'%c' %d\n", buf[0], buf[0]);

	return 0;
}

void perrorWin32() {
	LPTSTR message;
	DWORD err = GetLastError();

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		err,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR)&message,
		0, NULL);

	printf("error code %lu: %s", err, message);
	LocalFree(message);
}

