TraceLife

真正的幸福,在于对平淡生活的热爱……

导航

curses 库和 conio 库功能互换

Posted on 2008-06-09 19:21  hallo  阅读(789)  评论(0编辑  收藏  举报
They can conquer who believe they can. 
                             -- Virgil

  Curses 是一个用于类 Unix 系统的终端控制库,用来构建文本用户界面 [Text User Interface (TUI)] 的应用程序。名称来源于双关语(pun on) 【cursor optimization】。用来管理那些以字符终端(character-cell terminals)作为界面的应用程序,比如 VT100。

  Curses-based software 类型的软件通常都实现了 Curses 库,或其兼容库(比如 Ncurses 库)。Curses 库主要是用来在字符设备上创建“图形化”的应用程序,诸如通常使用的 SSH 和 Telnet 客户端等,在使用某些程序时,会以字符的方式呈现模拟 GUI 界面。

  Curses 通常用于类 Unix 系统,Windows 下也有对应的实现,不过在 Windows 下通常使用 conio 库完成相类似的任务。

 


  通常在 Windows 平台下用 conio 库实现的功能,当移植到 Linux 平台时需要使用 Curses 库进行替换。编译时加上 [-lcurses] 参数。

$ gcc test.c -lcurses 

test.c:2:27: error: curses.h: 没有那个文件或目录

 

 

  这个错误是由于没有安装对应的 Curses 库,在 Ubuntu 下可以利用下面的语句安装 Curses 库。

$ sudo apt-get install libncurses5-dev

  举例,下面的程序会从命令行读取用户输入的字符并判断字符是否为 q

  》》》 

/*
    Turbo C Version
*/
#include <stdio.h>
#include <conio.h>

int
main(void)
{
    char c;

    while((c = getch()) != 'q')
    {
        printf("You have enter %c\n", c);
    }
}

  将上面的程序一直到 Linux 下,则必须使用 curses 库所提供的功能。

  》》》 

/*
    使用 cursee 库从客户端获取字符
*/
#include <stdio.h>
#include <curses.h>

int
main(void)
{
    char c;
    int row = 0;
    int col = 0;

    initscr();
    while((c = getch()) != 'q') {
        // 将游标移动到 row 行,col 列
        move(row++, col);
        // 调用 delch() insch() 函数,用 c 替换当前字符
        delch();
        insch(c);
    }
    endwin();

    return 0;
}

  需要注意的是,在使用 curses 库函数时,要先使用 initscr() 函数进行窗口的初始化操作,在程序结束时,调用 endwin() 返回到控制台并离开。

  》》》  

/*
     cursee 库使用模板
*/
#include <stdio.h>
#include <curses.h>

int
main(void)
{
	...
    initscr();
	...	
    endwin();
	...
	
    return 0;
}