Linux下实现“任意键继续”

来源:互联网 发布:小米电动牙刷 知乎 编辑:程序博客网 时间:2024/06/05 10:11
     因为getch()函数不回显,并在终端输入不需要回车。所以可在很多程序灵活运用

     以下为摘录网络上的代码:


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

int getch();

void press_key();

int main()
{
   printf("Hello world!\n");
   press_key();
   return 0;
}

void press_key()
{
   printf("Press any key to continue...\n");
   getch();
}

int getch()
{
   struct termios tm, tm_old;
   int fd = STDIN_FILENO,c;

   if (tcgetattr(fd, &tm) < 0)
   {
      return -1;
   }

   tm_old = tm;
   cfmakeraw(&tm);

   if (tcsetattr(fd, TCSANOW, &tm) < 0)
   {
      return -1;
   }

   c = fgetc(stdin);

   if (tcsetattr(fd,TCSANOW,&tm_old) < 0)
   {
      return -1;
   }

   return c;
}
         
0 0
原创粉丝点击