歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux 按任意鍵繼續而不必等回車

Linux 按任意鍵繼續而不必等回車

日期:2017/2/28 16:47:29   编辑:Linux教程

最近在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公社網站無關。其原創性以及文中陳述文字和內容未經本站證實,對本文以及其中全部或者部分內容、文字的真實性、完整性、及時性本站不作任何保證或承諾,請讀者僅作參考,並請自行核實相關內容。

Copyright © Linux教程網 All Rights Reserved