LoginSignup
1
1

More than 1 year has passed since last update.

C言語 readline関数

Last updated at Posted at 2021-08-09

はじめに

readline関数はMacのデフォルト環境には入っていません。
以下のコマンドでインストールする必要があります。

brew install readline

コンパイル時にも lオプションでライブラリを指定する必要があります。

gcc main.c -lreadline

readline

ユーザから編集機能付きで一行を受け取ります。

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>

char *readline (char *prompt);

readlineは、promptをプロンプトとして使用して、端末から行を読み取り、それを返します。

プロンプトがNULLまたは空の文字列の場合、プロンプトは発行されません。

返される行はmalloc(3)で割り当てられます。
呼び出し元は、終了時にそれを解放する必要があります。

返された行では最後の改行が削除されているため、行のテキストのみが残ります。

返り値

readlineは、読み取った行のテキストを返します。

空白行は空の文字列を返します。行の読み取り中にEOFが検出され、その行が空の場合、NULLが返されます。EOFが空でない行で読み取られた場合、それは改行として扱われます。

コンパイル方法

サンプルコード

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>

int main()
{
    char *line = NULL;

    while (1)
    {
        line = readline("> ");
        if (line == NULL || strlen(line) == 0)
        {
            free(line);
            break;
        }
        printf("line is '%s'\n", line);
        add_history(line);
        free(line);
    }
    printf("exit\n");
    return 0;
}

add_history関数を入れておくと、↑でヒストリーの参照ができます。

参考

readline(3) — Arch manual pages

The GNU Readline Libraryを使った - メモの日々(2008-03-19)

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1