/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... use read()/write().
 *
 *  ... use getch()/putch()/kbhit().
 */

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

/*
 * The basic stream I/O functions are:
 *  fgetc() blocking (wait for character)
 *          echo stdin to stdout
 *          cooked (convert "\r\n" to '\n')
 *  fputc() cooked (convert '\n' to "\r\n")
 *
 * The basic fd I/O functions are:
 *  read()  non-blocking (no wait for character)
 *          no echo
 *          raw (no conversion)
 *  write() raw (no conversion)
 *
 * Special functions for stdin/stdout:
 *  getch() blocking (wait for character)
 *          no echo
 *          raw (no conversion)
 *  putch() raw (no conversion)
 *  kbhit() return "char available"
 */
int
main(void)
{
	char c;

	/*
	 * Using read() on stdin:
	 * Non-blocking read raw char without echo.
	 */
	puts("read() loop...");
	while (read(fileno(stdin), &c, 1) != 1) ;

	/*
	 * Using write() on stdout:
	 * Raw write the char read by read().
	 */
	puts("write():");
	write(fileno(stdout), &c, 1);

	/*
	 * Using getch():
	 * Read raw char without echo from stdin.
	 */
	puts("\ngetch()...");
	c = getch();

	/*
	 * Using putch():
	 * Raw write the char read by getch() to stdout.
	 */
	puts("putch():");
	putch(c);

	/*
	 * Using kbhit():
	 * Check if char available from stdin.
	 */
	puts("\nkbhit() loop...");
	while (1) {

		/*
		 * Show when a key is hit, then
		 * remove the char with getch().
		 */
		if (kbhit()) puts("KEY HIT!"), getch();
	}
}
