Linux下的编程很大一部分都是命令行模式。可执行文件加上特定的参数。不过有时候需要在程序启动后,在输入一些字符串,程序做相应的反应。有时候就简单地使用scanf、cin以及getline之类的函数获取用户的输入。但此类函数的输入交互性很差。命令输入到一半,发现错误,怎么办?退格,delete,Home之类的键都当作一个字符输入,无法起到相应的作用。一般只有回车,在重新输入。很是郁闷。
那么,能不能做到像bash之类的shell下面,可以编辑命令的输入呢?为此专门下了bash的源码,终于从中发现readline这个函数库,可以解决这个问题。而且这个库一般在Linux中都有,不需要另外安装,在shell下:man readline,可以看到这个库的一些帮助文档。更为详细的文档可以在GNU Readline Library上找到。
使用时只需要简单的调用char* readline(const char *prompt),头文件为就可以了,该函数返回用户的输入,参数prompt只是提示信息而已。
有了readline函数,我们就可以简单的编辑输入命令了,比如使用退格,Home,End,Delete之类的键。如果,你需要更为高级的应用,请仔细阅读它的文档。还有一点值得指出的是,在用gcc编译的时候需要加上参数 -lreadline, -ltermcap,
也许,你还是不满足,觉得如果能像shell那样,按向下,向上键恢复已经输入的命令就好了。呵呵,没事,一切都帮你做好了。还有一个叫history的库,详细文档在GNU History Library上。使用起来也特别的简单。给出一段简单地实现命令编辑和恢复历史命令的函数:
/* A static variable for holding the line. */ static char *line_read = (char *)NULL; /* Read a string, and return a pointer to it. Returns NULL on EOF. */ char * rl_gets () { /* If the buffer has already been allocated, return the memory to the free pool. */ if (line_read) { free (line_read); line_read = (char *)NULL; } /* Get a line from the user. */ line_read = readline (“”); /* If the line has any text in it, save it on the history. */ if (line_read && *line_read) add_history (line_read); return (line_read); }
你需要做的只是简单地调用rl_gets()函数。一切都是那么的方便。当然,如果你不满足于使用想看看实现方式,可以去下载bash的源码,在bash-3.0/lib/readline/里面看到完整的源代码。