c 终端控制

时间:2023-03-08 16:56:29
c 终端控制
#include <stdio.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h> char my_getch()
{
int c=;
struct termios org_opts, new_opts;
int res=; res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==); memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts); c=getchar();
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res==);
return c;
}

键盘输入不回显处理

/×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××/

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <curses.h>
#include <term.h>
#include <unistd.h> static int peek_character = -; int kbhit()
{
char ch;int x;
int nread;
struct termios old_settings,new_settings; tcgetattr(STDIN_FILENO,&old_settings);
new_settings=old_settings;
new_settings.c_lflag &=~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ECHOPRT|ECHOKE|ICRNL) ;
new_settings.c_cc [VMIN]= ;
new_settings.c_cc [VTIME]= ;
tcsetattr(STDIN_FILENO,TCSANOW,&new_settings); if(peek_character!=-)
x= ;
new_settings.c_cc [VMIN]= ;
tcsetattr(STDIN_FILENO,TCSANOW,&new_settings); nread=read(,&ch,);
new_settings.c_cc [VMIN]= ;
tcsetattr(STDIN_FILENO,TCSANOW,&new_settings); if(nread==) {
peek_character=ch;
x=;
}
else x=;
tcsetattr(STDIN_FILENO,TCSANOW,&old_settings);
return x;
}
int readch()
{
char ch; if(peek_character!=) {
ch=peek_character;
peek_character=-;
return ch;
}
read(,&ch,);
return ch;
}

检测有键盘输入并返回键值