來源:http://skyishuman.iteye.com/blog/1672476
curses庫是一組函數,程序員可以用它們來設置光標的位置和終端屏幕上顯示的字符樣式。curses庫最初是由UCB的開發小組開發的。大部分控制終端屏幕的程序使用curses。曾經由一組簡單的函數組成的庫現在包括了許多復雜的特性。
Ubuntu下安裝方法:
sudo apt-get install libncurses5-dev
(如果發現找不到這個包,使用命令 sudo apt-get update 更新下包源)
curses的基本用法如下:
1. 包含頭文件:curses.h
2. 編譯時應加上鏈接語句-lcurses,如:gcc temp.c -o temp -lcurses
3. 重要的函數:
initscr():初始化curses庫和ttty。(在開始curses編程之前,必須使用initscr()這個函數來開啟curses模式)
endwin():關閉curses並重置tty。(結束curses編程時,最后調用的一個函數)
move(y,x): 將游標移動至 x,y 的位置.
getyx(win,y,x): 得到目前游標的位置. (請注意! 是 y,x 而不是&y,&x )
clear() and erase(): 將整個螢幕清除. (請注意配合refresh() 使用)
echochar(ch): 顯示某個字元.
addch(ch): 在當前位置畫字符ch
mvaddch(y,x,ch): 在(x,y) 上顯示某個字元. 相當於呼叫move(y,x);addch(ch);
addstr(str): 在當前位置畫字符串str
mvaddstr(y,x,str): 在(x,y) 上顯示一串字串. 相當於呼叫move(y,x);addstr(str);
printw(format,str): 類似 printf() , 以一定的格式輸出至螢幕.
mvprintw(y,x,format,str): 在(x,y) 位置上做 printw 的工作. 相當於呼叫move(y,x);printw(format,str);
getch(): 從鍵盤讀取一個字元. (注意! 傳回的是整數值)
getstr(): 從鍵盤讀取一串字元.
scanw(format,&arg1,&arg2...): 如同 scanf, 從鍵盤讀取一串字元.
beep(): 發出一聲嗶聲.
box(win,ch1,ch2): 自動畫方框
refresh(): 使屏幕按照你的意圖顯示。比較工作屏幕和真實屏幕的差異,然后refresh通過終端驅動送出那些能使真實屏幕於工作屏幕一致的字符和控制碼。(工作屏幕就像磁盤緩存,curses中的大部分的函數都只對它進行修改)
standout(): 啟動standout模式(一般使屏幕發色)
standend(): 關閉standout模式
常用的初始化函數集合:
void initial()
{
initscr(); //開啟curses模式
cbreak(); //開啟cbreak模式,除了 DELETE 或 CTRL 等仍被視為特殊控制字元外一切輸入的字元將立刻被一一讀取
nonl(); //用來決定當輸入資料時, 按下 RETURN 鍵是否被對應為 NEWLINE 字元
noecho(); //echo() and noecho(): 此函式用來控制從鍵盤輸入字元時是否將字元顯示在終端機上
intrflush(stdscr,false);
keypad(stdscr,true); //當開啟 keypad 後, 可以使用鍵盤上的一些特殊字元, 如上下左右>等方向鍵
refresh(); //將做清除螢幕的工作
}
#include <stdio.h>
#include <curses.h>
int main()
{
initscr();
clear();
move(10,20);
addstr("hello,world");
move(LINES-1,0);
refresh();
getch();
endwin();
return 0;
}
以上是curses庫的一些簡單的應用。