Cover V06, I04
Article
Listing 1
Sidebar 1

apr97.tar


Listing 1: ret_char

#include <stdio.h>
#include <termio.h>
#include <fcntl.h>

main()
{
printf("%c\n", ret_char());
}

/* ret_char.c.  System V dependent.
* This function is designed to return the ascii value of a
* single character * as long as it's alphanumeric, an interrupt,
* control-c or a Carriage Return.  This function only accepts
* an alphanumeric, an interrupt or control-c.
*
*  1.  Save original terminal settings.
*  2.  Turn off canonial mode and echoing.
*  3.  Get the character.
*  4.  Reset the original terminal settings.
*  5.  Return the character.
*
* Use this in a shell script as such:
* achar=`ret_char`
* echo "achar is: "$achar
*/
int ret_char()
{
struct termio tsave, chgit;
int c;

/* save original terminal settings */
if(ioctl(0, TCGETA, &tsave) == -1)
{
perror("bad term setting");
exit(1);
}
chgit = tsave;

/* turn off canonial mode and echoing */
chgit.c_lflag &= ~(ICANON|ECHO);
chgit.c_cc[VMIN] = 1;
chgit.c_cc[VTIME] = 0;

/* modify terminal settings */
if(ioctl(0, TCSETA, &chgit) == -1)
perror("can't modify terminal settings ");

while (1)
{ /* break when an alphanumeric, interrupt,
control-c, CR is pressed */
c = getchar();
/* CR is ascii value 13, interrupt is -1, control-c is 3 */
if(isalnum(c) || c == '\r' || c == '\n' || c == '\b'
|| c == -1 || c == 3)
break;
}

/* reset to original terminal settings */
if(ioctl(0, TCSETA, &tsave) == -1)
{
perror("can't reset original setting");
exit(1);
}
/* return the character */
return(c);
}

/* End of File */