Linux从控制台一次读取一个字符,无需等待回车键

原文:http://www.cnblogs.com/zhouyinhui/archive/2010/10/12/1849011.html

读取字符嘛,可以使用getchar(),getch()等等函数,但它们都需要等待回车键以结束输入,而不是按下键盘时立即响应,看上去不那么“实时”。

如果是在windows平台下的话,可以使用conio.h下的_getch()函数,注意是以下划线开头的,msdn链接在这里

在linux下貌似没有找到类似的函数... 不过可以使用一个比较BT的方式来实现:更改控制台设置。

复制代码
#include  < termios.h >

static   struct  termios oldt;

// restore terminal settings
void  restore_terminal_settings( void )
{
    
//  Apply saved settings
    tcsetattr( 0 , TCSANOW,  & oldt); 
}

// make terminal read 1 char at a time
void  disable_terminal_return( void )
{
    
struct  termios newt;
    
    
// save terminal settings
    tcgetattr( 0 & oldt); 
    
// init new settings
    newt  =  oldt;  
    
// change settings
    newt.c_lflag  &=   ~ (ICANON  |  ECHO);
    
// apply settings
    tcsetattr( 0 , TCSANOW,  & newt);
    
    
// make sure settings will be restored when program ends
    atexit(restore_terminal_settings);
}
复制代码

 

下面是一个demo程序,复制粘贴试用吧:

复制代码
#include  < stdio.h >
#include 
< stdlib.h >
#include 
< termios.h >

static   struct  termios oldt;

// restore terminal settings
void  restore_terminal_settings( void )
{
    
// Apply saved settings
    tcsetattr( 0 , TCSANOW,  & oldt); 
}

// make terminal read 1 char at a time
void  disable_terminal_return( void )
{
    
struct  termios newt;
    
    
// save terminal settings
    tcgetattr( 0 & oldt); 
    
// init new settings
    newt  =  oldt;  
    
// change settings
    newt.c_lflag  &=   ~ (ICANON  |  ECHO);
    
// apply settings
    tcsetattr( 0 , TCSANOW,  & newt);
    
    
// make sure settings will be restored when program ends
    atexit(restore_terminal_settings);
}

int  main()
{
    
int  ch;
    
    disable_terminal_return();
    
    printf(
" press your keyboard\n " );
    
/*  Key reading loop  */
    
while  ( 1 ) {
        ch 
=  getchar();
        
if  (ch  ==   ' Q ' return   0 ;   /*  Press 'Q' to quit program  */
        printf(
" \tYou pressed %c\n " , ch);
    }
    
    
return   0 ;
}
复制代码

 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值