手机版
你好,游客 登录 注册
背景:
阅读新闻

Linux 按任意键继续而不必等回车

[日期:2009-04-24] 来源:chinaunix.net  作者: ubuntuer [字体:大 中 小]

最近在Linux下写程序有个小必要获得一个字符就返回,一般情况下我们不是都要回车吗...  终端通常在标准(canonical)模式,在此模式输入总是经编辑后以行读入。你可以设置终端为非标准(non-canonical)模式,而在此模式下你可以设置在输入传递给你的程序前读入多少字符。你也可以设定非标准模式的计时器为0,这个计时器根据设定的时间间隔清空你的缓冲区。这样做使你可以使用‘getc()’函数立即获得用户的按键输入。我们使用的‘tcgetattr()’函数和‘tcsetattr()’函数都是在POSIX中定义用来操纵‘termios’结构的。

#include <stdlib.h>
#include <stdio.h>

#include <termios.h>
#include <string.h>

static struct termios stored_settings;

void
set_keypress (void)
{
  struct termios new_settings;

  tcgetattr (0, &stored_settings);

  new_settings = stored_settings;

  /* Disable canonical mode, and set buffer size to 1 byte */
  new_settings.c_lflag &= (~ICANON);
  new_settings.c_cc[VTIME] = 0;
  new_settings.c_cc[VMIN] = 1;

  tcsetattr (0, TCSANOW, &new_settings);
  return;
}

void
reset_keypress (void)
{
  tcsetattr (0, TCSANOW, &stored_settings);
  return;
}

int main()
{
 int c = 0;
 printf("begin input one char\n");
 set_keypress();
  while(1)
  {
    c = getchar();
    printf("your input is %c\n",c);
    if(c == (int)'q')
      break;
   }
 reset_keypress();
 printf("end input one char\n");
 return 0;
}


[root@mip-172024149048 char]# gcc -Wall -o char char.c
[root@mip-172024149048 char]# ./char
begin input one char
syour input is s
cyour input is c

郑重声明:本文仅代表作者个人观点,与Linux公社网站无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。

linux
相关资讯       Linux教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款