首页 > 其他分享 >libreadline-dev介绍和例子

libreadline-dev介绍和例子

时间:2023-08-15 17:05:56浏览次数:34  
标签:return libreadline dev char int 例子 arg line com

Author [email protected]

Date Aug. 15, 2023

Description libreadline-dev介绍和例子

简介

在实现一个类shell的程序的时候,可能需要使用到命令补全以及命令历史记录。这时候就可以使用libreadline库,这是一个GNU开发的库,官网是:The GNU Readline Library

这个库主要提供命令补全、命令修改以及命令历史,当然命令历史有一个单独的库叫做History library,但这里就一起装一起用了,而且包管理器也没有区分(apt show libreadline-dev可以查看依赖包)。

当然最好的教程就是官网的文档。第一部分算是介绍,第二部分是开发,上面也给了很多例子,可以直接照抄了。

安装

  • apt系:sudo apt install libreadline-dev
  • yum系:sudo yum install readline-devel
  • 源码:没试过,下面是我猜测的,不过GNU的源码安装都基本是同样命令
    git clone git://git.savannah.gnu.org/readline.git
    ./configure
    make
    sudo make install
    sudo ldconfig
    

使用

它主要有两个头文件,<readline/readline.h><readline/history.h>,前者就是命令行编辑、命令补全等,后者就是命令历史。如果要查看所有的头文件,那就去/usr/include/readline/下查看。

默认情况下,readline只提供对文件名的补全。这个例子介绍了下,主要就两个函数:

  • readline(prompt_string):获取用户输入,可以补全文件名
  • add_history(input_string):用户输入加入历史,可以使用上下箭头进行切换。

但是使用readline一般是为了自定义命令。这个例子的源码在GNU Readline Library的教程库中,叫做fileman.c。我重新整理了下这个例子,原来的函数参数写法好像是C标准还没有成立时的写法,不过无所谓了,是能看懂的。

在这个例子中,其实主要还是看readline相关的函数吧,其它的再学习。例子中,定义了一个COMMAND数据结构,然后定义了该数据结构的数组,描述各个命令、执行函数以及对应含义。在这个例子中和readline相关:

  • 一个是add_history,就是把命令加入历史记录。
  • 一个是rl_attempted_completion_function,这是一个指针变量,指向命令补全的函数,这个函数fileman_completion中text就是用户已输入,start和end为在rl_line_buffer中的边界。start不一定为0,那是因为命令补全不一定是从第一个单词开始的。例如ls bu,要补全为build,那么start就是3,end是5。
  • 一个是rl_completion_matches,创建matches,相当于是返回的是所有匹配的命令以及文件。如果没有输入,就返回所有的命令了;部分输入有匹配返回匹配,没有匹配返回NULL。
  • 当然还有一堆的执行函数,以com_开头,那就是具体的命令的逻辑了。

简单编译使用

gcc -o fileman fileman.c -I/usr/include/readline -lreadline

更多功能还是参考官网文档吧。

源码

<details> <summary>fileman.c整理后的源码</summary>

/* readline exmaple code getting from
 *  https://tiswww.case.edu/php/chet/readline/readline.html#A-Short-Completion-Example
 */

/* fileman.c -- A tiny application which demonstrates how to use the
 *  GNU Readline library.  This application interactively allows users
 *  to manipulate files and their modes. */

#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <locale.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <readline/readline.h>
#include <readline/history.h>

/* The name of this program, as taken from argv[0]. */
static char *progname;

/* When non-zero, this global means the user is done using this program. */
static int done;

/* String to pass to system ().  This is for the LIST, VIEW and RENAME
 *  commands. */
static char syscom[1024];

/* The names of functions that actually do the manipulation. */
int com_list(char *);
int com_view(char *);
int com_rename(char *);
int com_stat(char *);
int com_pwd(char *);
int com_delete(char *);
int com_help(char *);
int com_cd(char *);
int com_quit(char *);

/* A structure which contains information on the commands this program
 *  can understand. */
typedef struct {
    char *name;                /* User printable name of the function. */
    rl_icpfunc_t *func;        /* Function to call to do the job. */
    char *doc;                 /* Documentation for this function.  */
} COMMAND;

/* commands array */
COMMAND commands[] = {
    { "cd", com_cd, "Change to directory DIR" },
    { "delete", com_delete, "Delete FILE" },
    { "help", com_help, "Display this text" },
    { "?", com_help, "Synonym for `help'" },
    { "list", com_list, "List files in DIR" },
    { "ls", com_list, "Synonym for `list'" },
    { "pwd", com_pwd, "Print the current working directory" },
    { "quit", com_quit, "Quit using Fileman" },
    { "rename", com_rename, "Rename FILE to NEWNAME" },
    { "stat", com_stat, "Print out statistics on FILE" },
    { "view", com_view, "View the contents of FILE" },
    { (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL }
};

/* Look up NAME as the name of a command, and return a pointer to that
 *  command.  Return a NULL pointer if NAME isn't a command name. */
COMMAND* find_command (char *name)
{
    register int i;

    for (i = 0; commands[i].name; i++)
        if (strcmp (name, commands[i].name) == 0)
            return (&commands[i]);

    return ((COMMAND *)NULL);
}

/* Execute a command line. */
int execute_line (char *line)
{
    register int i;
    COMMAND *command;
    char *word;

    /* Isolate the command word. */
    i = 0;
    while (line[i] && whitespace (line[i]))
        i++;
    word = line + i;

    while (line[i] && !whitespace (line[i]))
        i++;

    if (line[i])
        line[i++] = '\0';

    command = find_command (word);

    if (!command)
    {
        fprintf (stderr, "%s: No such command for FileMan.\n", word);
        return (-1);
    }

    /* Get argument to command, if any. */
    while (whitespace (line[i]))
        i++;

    word = line + i;

    /* Call the function. */
    return ((*(command->func)) (word));
}

/* Strip whitespace from the start and end of STRING.  Return a pointer
 *  into STRING. */
char* stripwhite (char *string)
{
    register char *s, *t;

    for (s = string; whitespace (*s); s++)
        ;

    if (*s == 0)
        return (s);

    t = s + strlen (s) - 1;
    while (t > s && whitespace (*t))
        t--;
    *++t = '\0';

    return s;
}

/* Function which tells you that you can't do this. */
void too_dangerous (char *caller)
{
    fprintf (stderr,
            "%s: Too dangerous for me to distribute.  Write it yourself.\n",
            caller);
}

/* **************************************************************** */
/*                                                                  */
/*                  Interface to Readline Completion                */
/*                                                                  */
/* **************************************************************** */

/* Generator function for command completion.  STATE lets us know whether
 *  to start from scratch; without any state (i.e. STATE == 0), then we
 *  start at the top of the list. */
char * command_generator (const char *text, int state)
{
    static int list_index, len;
    char *name;

    /* If this is a new word to complete, initialize now.  This includes
     *  saving the length of TEXT for efficiency, and initializing the index
     *  variable to 0. */
    if (!state)
    {
        list_index = 0;
        len = strlen (text);
    }

    /* Return the next name which partially matches from the command list. */
    while ((name = commands[list_index].name))
    {
        list_index++;

        if (strncmp (name, text, len) == 0)
            return (strdup(name));
    }

    /* If no names matched, then return NULL. */
    return ((char *)NULL);
}

/* Attempt to complete on the contents of TEXT.  START and END bound the
 * region of rl_line_buffer that contains the word to complete.  TEXT is
 * the word to complete.  We can use the entire contents of rl_line_buffer
 * in case we want to do some simple parsing.  Return the array of matches,
 * or NULL if there aren't any. */
char **fileman_completion (const char *text, int start, int end)
{
    char **matches;

    matches = (char **)NULL;

    /* If this word is at the start of the line, then it is a command
     *  to complete.  Otherwise it is the name of a file in the current
     *  directory. */
    if (start == 0)
        matches = rl_completion_matches (text, command_generator);

    return (matches);
}



/* Tell the GNU Readline library how to complete.  We want to try to complete
 *  on command names if this is the first word in the line, or on filenames
 *  if not. */
void initialize_readline ()
{
    /* Allow conditional parsing of the ~/.inputrc file. */
    rl_readline_name = "FileMan";

    /* Tell the completer that we want a crack first. */
    rl_attempted_completion_function = fileman_completion;
}

/* Return non-zero if ARG is a valid argument for CALLER, else print
 *  an error message and return zero. */
int valid_argument (char *caller, char *arg)
{
    if (!arg || !*arg)
    {
        fprintf (stderr, "%s: Argument required.\n", caller);
        return (0);
    }

    return (1);
}


/* **************************************************************** */
/*                                                                  */
/*                       FileMan Commands                           */
/*                                                                  */
/* **************************************************************** */

/* List the file(s) named in arg. */
int com_list (char *arg)
{
    if (!arg)
        arg = "";

    sprintf (syscom, "ls -FClg %s", arg);
    return (system (syscom));
}

int com_view (char *arg)
{
    if (!valid_argument ("view", arg))
        return 1;

#if defined (__MSDOS__)
    /* more.com doesn't grok slashes in pathnames */
    sprintf (syscom, "less %s", arg);
#else
    sprintf (syscom, "more %s", arg);
#endif
    return (system (syscom));
}

int com_rename (char *arg)
{
    too_dangerous ("rename");
    return (1);
}

int com_stat (char *arg)
{
    struct stat finfo;

    if (!valid_argument ("stat", arg))
        return (1);

    if (stat (arg, &finfo) == -1)
    {
        perror (arg);
        return (1);
    }

    printf ("Statistics for `%s':\n", arg);

    printf ("%s has %ld link%s, and is %ld byte%s in length.\n",
            arg,
            finfo.st_nlink,
            (finfo.st_nlink == 1) ? "" : "s",
            finfo.st_size,
            (finfo.st_size == 1) ? "" : "s");
    printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime));
    printf ("      Last access at: %s", ctime (&finfo.st_atime));
    printf ("    Last modified at: %s", ctime (&finfo.st_mtime));
    return (0);
}

int com_delete (char *arg)
{
    too_dangerous ("delete");
    return (1);
}

/* Print out help for ARG, or for all of the commands if ARG is
 *  not present. */
int com_help (char *arg)
{
    register int i;
    int printed = 0;

    for (i = 0; commands[i].name; i++)
    {
        if (!*arg || (strcmp (arg, commands[i].name) == 0))
        {
            printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc);
            printed++;
        }
    }

    if (!printed)
    {
        printf ("No commands match `%s'.  Possibilities are:\n", arg);

        for (i = 0; commands[i].name; i++)
        {
            /* Print in six columns. */
            if (printed == 6)
            {
                printed = 0;
                printf ("\n");
            }

            printf ("%s\t", commands[i].name);
            printed++;
        }

        if (printed)
            printf ("\n");
    }
    return (0);
}

/* Change to the directory ARG. */
int com_cd (char *arg)
{
    if (chdir (arg) == -1)
    {
        perror (arg);
        return 1;
    }

    com_pwd ("");
    return (0);
}

/* Print out the current working directory. */
int com_pwd (char *ignore)
{
    char dir[1024], *s;

    s = getcwd (dir, sizeof(dir) - 1);
    if (s == 0)
    {
        printf ("Error getting pwd: %s\n", dir);
        return 1;
    }

    printf ("Current directory is %s\n", dir);
    return 0;
}

/* The user wishes to quit using this program.  Just set DONE non-zero. */
int com_quit (char *arg)
{
    done = 1;
    return (0);
}

int main (int argc, char **argv)
{
    char *line, *s;

    setlocale (LC_ALL, "");

    progname = argv[0];

    initialize_readline ();    /* Bind our completer. */

    /* Loop reading and executing lines until the user quits. */
    for ( ; done == 0; )
    {
        line = readline ("FileMan: ");

        if (!line)
            break;

        /* Remove leading and trailing whitespace from the line.
         *  Then, if there is anything left, add it to the history list
         *  and execute it. */
        s = stripwhite (line);

        if (*s)
        {
            add_history (s);
            execute_line (s);
        }

        free (line);
    }
    exit (0);
}

</details>

标签:return,libreadline,dev,char,int,例子,arg,line,com
From: https://blog.51cto.com/basilguo/7090426

相关文章

  • 界面组件DevExpress Reporting——支持图表本地化和可绑定属性
    DevExpressReporting是.NETFramework下功能完善的报表平台,它附带了易于使用的VisualStudio报表设计器和丰富的报表控件集,包括数据透视表、图表,因此您可以构建无与伦比、信息清晰的报表。在最近的更新(v23.1)中,官方扩展了DevExpress .NETReports(即XRChart报表控件)中与图表......
  • SAP Infinite Transaction with Update 的一个具体例子
    在计算机科学中,事务是一组操作的集合,这些操作要么全部成功执行,要么全部回滚,以确保数据的一致性和完整性。某些企业管理软件的业务事务,被实现为InfiniteTransaction,以节省事务开始时的初始化时间。这种设计离不开乐观锁,因为乐观锁在更改实际发生之前不会转换为排他锁(E锁,全......
  • 生成式AI时代的AI Infra—从DevOps->MLOps->LLMOps
    来源:https://zhuanlan.zhihu.com/p/640725385 距离上次讲LLM相关的内容已经过去2个月了LLMasController—无限拓展LLM的能力边界,本文想要从AIInfra的角度出发,从更宏观的角度看GenerativeAI对AIInfra生态产生的变化,本文不局限于LLM,文中提到的LLM泛指一切GenerativeAI或者......
  • WinForm DevExpress 添加行内按钮
    1.在设计器里面添加一列,设置单元格不可编辑、只读属性   2.在所在GridView属性里面添加CustomDrawCell事件与RowCellClick事件privatevoidgvMain_CustomDrawCell(objectsender,DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgse){......
  • Aidlux玩转例子—换脸。
    玩一玩AidLux应用中心的Demo。  1.在AidLux平台例子中心,选择一个样例。2.点击RunNow进行运行。3.通过摄像头捕捉人脸,与明星互换面容,可以看看你是哪个明星。 展现流程如下:https://www.bilibili.com/video/BV1gp4y1g782/?vd_source=706eedffe7949070fa3c396c34f4e789......
  • 推荐工具!使终端便于 DevOps 和 Kubernetes 使用
    如果你熟悉DevOps和Kubernetes的使用,就会知道命令行界面(CLI)对于管理任务有多么重要。好在现在市面上有一些工具可以让终端在这些环境中更容易使用。在本文中,我们将探讨可以让工作流程简化的优秀工具,帮助你在DevOps和Kubernetes中自如地浏览终端。 ZshZsh(ZShell)是一......
  • 通过一个实例的例子,学习 SAP Fiori 应用中的 Draft Handling(草稿机制)
    SAPFiori应用里的DraftHandling(草稿处理)是一种机制,用于在SAP业务数据的编辑过程中,实时保存未提交的更改。这样的机制允许用户在多个会话或者繁琐的表单填写步骤中,逐渐构建和修改数据,并在需要时将其提交。DraftHandling在SAPFiori应用中起到重要的作用,可以在不中断现有......
  • 通过重写js脚本文件的例子看文件操作
    有以下文件:相对路径:"Resources/MainWindow/MsgHtml/msgtmpl.txt"文件内容: 要求:由于将要进行通信,我们将external0这个网页对象作为qq的发送者,这是可行的,然而接收者只有这一个对象external是不够的,我们将上面的txt文件作为一个初始版本,最后要进行更改,并最终要写入js文件中。......
  • t113-c-lvgl8-gui例子
    其实tina官方提供了littellvgl的例子,既然找不到原因(可能是8.39的bug),那就看看官方怎么写的。路径主路径是在这里:makefile:显然这makefile是显示在应用层开发的main中:在littlelvgl中有个lvinit是用来初始化内存等等东西的,而在我写的程序中并没有写入写入后仍然不行,看来不是......
  • Devexpress xtraTabControl1实现多标签页选项卡,关闭选项卡,刷新重新加载
    //选项卡Dictionary<string,XtraTabPage>dictXtraTabPage=newDictionary<string,XtraTabPage>();Dictionary<string,Form>dictXtraForm=newDictionary<string,Form>();publicvoidShowMDIForm(string......