Windows 上的 C 語言有個好用的 conio.h,裡面提供了不少控制台操作函數;Linux 並沒有這個標頭檔,需要的功能得自己動手做。以下是最常被用到的兩個。
最省事的做法是呼叫外部指令:
void clrscr(void)
{
system("clear"); // 需要 stdlib.h
}
若不想 fork 一個行程,也可以直接輸出 ANSI 序列 printf("\033[2J\033[1;1H"),效果相同且更快。
核心技巧是先用 stty -echo 關掉終端的輸入回顯,讀完再打開:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
printf("Input a char:");
system("stty -echo"); // 關閉回顯
c = getchar();
system("stty echo"); // 恢復回顯
printf("You have inputed:%c \n", c);
return 0;
}
這樣使用者在按鍵時螢幕上不會出現該字元,直到程式自己把它印出來。
system() 每次都要啟動一個 shell,成本不低。更正規的方式是直接操作 termios:
#include <termios.h>
#include <unistd.h>
int getch(void)
{
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO); // 關掉行緩衝與回顯
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
這個版本不需要按 Enter 就能取到字元,也就是真正的「無回應輸入」。conio.h 裡的 kbhit()、textcolor()、gotoxy() 等函數,都可以用 termios 與 ANSI 轉義序列逐一補上。