您的位置:首页 > 其它

Unix下如何直接获取键盘输入而不需要以回车作为结束符的方法总结

2008-12-17 16:23 429 查看
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <curses.h>

//sttyコマンドは標準出力で使用される端末の設定と確認を行うことができます。
//コマンドリファレンスはこちらを参考に。
//http://www.linux.or.jp/JM/html/GNU_sh-utils/man1/stty.1.html

int keyInput1()
{
char ab_Chr[250];
int gi_Tty;
/* 端末を入力モードでオープン */
if((gi_Tty = open("/dev/tty",O_RDONLY)) == -1)/* 異常時 */{
/* 異常で復帰 */
return -1;
}
system("stty raw -echo");

read(gi_Tty, ab_Chr, 1);
close(gi_Tty);
system("stty -raw echo");
printf("%c/n",ab_Chr[0]);
return ab_Chr[0];
}

int keyInput2()
{
char ab_Chr[250];
char c;
/*
*ioctl() would be better here; only lazy
*programmers do it this way:
*/

system("/bin/stty raw");
c=getchar();
system("/bin/stty -raw");
return c;
}

//terminalの属性を修正する
int keyInput3()
{

int c;
struct termios new_settings;
struct termios stored_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
c = getchar();
tcsetattr(0,TCSANOW,&stored_settings);

return c;
}

//curscrライブラリで実現する
int keyInput4()
{

WINDOW *curscr, *stdscr;
unsigned char c,b,a,buf[32];

stdscr = initscr();
//clear();
c=getch();
printw("/n");
//printw("c= %c/n",c);
refresh();
endwin();

return c;
}

int main()
{
char t_ReadBuf[250];

while(1)
{
int c ;
printf("Call keyInput1/n");
c=keyInput1();
printf("Input c=%c/n",c);

printf("/n");

printf("Call keyInput2/n");
c=keyInput2();
printf("/nInput c=%c/n",c);

printf("/n");

printf("Call keyInput3/n");
c=keyInput3();
printf("/nInput c=%c/n",c);

printf("Call keyInput4/n");
c=keyInput4();
printf("/nInput c=%c/n",c);

if (c == 'q')
{
return 0;
}
}

}

//cc KeyInput.c -l curses
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐