Skip to content

Instantly share code, notes, and snippets.

@aont

aont/get_char.cpp

Created Feb 28, 2011
Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
struct getch_flag
{
char line:1;
char echo:1;
getch_flag() : line(0), echo(0) {}
} flag;
int get_char();
int main(int argc, char* argv[])
{
int result;
while((result=getopt(argc,argv,"le"))!=-1){
switch(result){
case 'l':
flag.line = 1;
break;
case 'e':
flag.echo = 1;
break;
case '?':
return EXIT_FAILURE;
break;
}
}
return get_char();
}
int get_char()
{
struct termios save_term;
struct termios temp_term;
char ch;
/* get term attributes */
errno = 0;
if(tcgetattr(fileno(stdin), &save_term) == -1){
perror("tcgetattr failure");
return EXIT_FAILURE;
}else{
temp_term = save_term;
}
/* non canonical */
temp_term.c_lflag &= ~ICANON;
/* finish read char */
temp_term.c_cc[VMIN] = 1;
/* no echo */
if(!flag.echo)
temp_term.c_lflag &= ~ECHO;
errno = 0;
if(tcsetattr(fileno(stdin), TCSANOW, &temp_term) == -1){
perror("tcsetattr(temp_term) failure");
return EXIT_FAILURE;
}
if(flag.line) {
while(1) {
ch = fgetc(stdin);
if(ch == '\r' || ch == '\n'){
break;
} else {
fputc(ch, stdout);
}
}
} else {
ch = fgetc(stdin);
fputc(ch, stdout);
}
/* reset */
errno = 0;
if(tcsetattr(fileno(stdin), TCSANOW, &save_term) == -1){
perror("tcsetattr(save_term) failure");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment