linux下C语言实现按任意键继续~~

这篇博客介绍了如何在Linux下使用C语言编写程序,实现在标准输入中读取单个字符并按任意键继续的功能。通过设置终端属性禁用canonical模式,设置缓冲区大小为1字节,实现了实时读取用户输入的功能。示例代码中包含函数set_keypress()用于改变终端设置,reset_keypress()用于恢复原设置。用户输入'q'时程序结束。
 

#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公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2009-04/19606.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值