readlineの使い方
Q. まず何をしたらいいの?
A. readline機能とhistory機能を使うために、readline.hとhistory.hをincludeしよう。
#include <readline/readline.h> #include <readline/history.h>
Q. どうやって使うの?
A. 基本の使い方は、関数readlineを呼べばいい。
>>_
("_"は半角スペース)
このようなプロンプトにして、入力文字列をcommandに代入したければ、
char *command; ... command = readline(">> ");
とすればいいよ。readlineの引数がプロンプト記号として標準出力に表示され、
入力されたコマンド文字列へのポインタがcommandに代入されるよ。
(引数は、NULLや空文字""でも可。)
[注意]
ただし、readline関数はmalloc()で領域を確保してその先頭アドレスを返すので、
きちんとcommandをfree()しなきゃダメだよ。
Q. このままだとhistory機能は無いよ?どうやって使うの?
A. history機能は、using_historyで初期化して、add_historyでhistoryに登録するんだ。
Q. うぇえん、この前のhistoryが見付からないよぉ。
A. 落ち着け、No.5。必ずその機能があるはずだ。
それはさておき、なんかしらのファイルに保存したり、そこから読み出したりする操作をしないと、記録されるわけはないわな。
そのための関数が、write_historyとread_historyだ。
使い方は、historyファイルの名前を".my_history"とすると、write_history(".my_history")とread_history(".my_history")だ。
(引数をNULLにすると、デフォルトの".history"がファイル名に選ばれるよ。)
ここまでの機能をまとめてみると、以下のようになるよ。これを改造して、自分の求めるプロンプトを作ってくれぃ。
#include <readline/readline.h> #include <readline/history.h> int main(void) { char *command; using_history(); read_history(".my_history"); // [ToDo]historyファイルが無いときの動作の検証 while(1) { command = readline(">> "); add_history(command); /* コマンドの処理 */ free(command); } write_history(".my_history"); return 0; }
それとそれぞれの関数の定義。
char *readline(const char *prompt) void using_history(void) void add_history(const char *string) int read_history(const char *filename) int write_history(const char *filename)
参考: http://tiswww.case.edu/php/chet/readline/history.html
http://tiswww.case.edu/php/chet/readline/readline.html
http://ppwww.phys.sci.kobe-u.ac.jp/~akusumoto/program/detail.php?d=c/10-other/readline