对Gnu_ReadLine库中的rl_gets()函数的解释

Gnu_ReadLine库中的rl_gets()函数的解释:

一、先不废话,先上代码:

  • 这里是相关链接🔗:gnu_realine库的官方文档
  • 注意,下面的代码来自上述链接,链接中的内容可以选择性阅读
  • *下面为rl_gets的官方代码*
  • !!! 注意,我们在这里的翻译是只翻译不解释,想看对代码的解释请向下翻
//我们已将官方的英文注释翻译成中文,并附上英文注释,以供参考

/* 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. */
/*读入字符串,并且返回一个指向它的指针,当输入EOF的时候,返回一个NULL指针*/
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);
}

二、代码各个位置的解释:

  • 先声明一个指针,之后要用这个指针指向用户输入的字符串:
//这句代码就不要多说了吧
static char *line_read = (char *)NULL;
//好吧,还是扯上几句,这里的指针先是指向空的,后续会指向用户输入的命令的字符串
  • 接下来就是对函数 rl_gets()地解释了
  • !!!注意,我们会将函数拆开来说
  1. 函数的标题头:
char *rl_gets ()//这句看不懂直接remake吧
//人道主义备注:这个函数返回一个指向char类型的指针
  1. 函数的刚开始的if语句:
//或者很多人就是栽在这个语句读不懂上
//先来看代码:
  /* If the buffer has already been allocated,
     return the memory to the free pool. */
    /*译:如果缓冲区已经被分配,那么需要先释放内存*/
  if (line_read)
    {
      free (line_read);
      line_read = (char *)NULL;
    }

(1)用Q&A解释:

​ Q:(1)为什么要有这个判断?(2)为什么要free?

​ A:

(1)解答:

在官方文档中有这样一句话:

The line readline returns is allocated with malloc(); the caller should free() the line when it has finished with it
  • 注意,这里的第一句话,readline指针指向的空间,也就用户输入的字符串那一串空间,咱们不可能预先知道大小,所以是由malloc()函数动态进行空间分配的,那么,情况分为两种:

​ a. 第一种情况,第一次使用的时候,自然而然地,指针刚被初始化,其值指向一个NULL, 故不用free()

​ b.第二种情况,就是用户在上一次输入EOF,也就是回车键,那自然而然地,不需要free, 因为指针就是指向NULL的

(2)为什么要free,STFW去,这都不知道,那实在不应该

  1. 用户的输入读取与命令行的输出:
line_read = readline ("");
//关于这句话的使用方法:
//例:
//line_read = readline("(numu)$>>");
//即,你可以"<在这里输入任何的提示>"
  • 这句代码就是让line_read指针,指向用户输入的那串字符串
  1. 最后一段代码
  /* 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);

  • 这一段代码是关于用户输入内容的判断,如果是非空格,或者非EOF,那么就将该输入存入history()函数,待用:

    if (line_read && *line_read)
        add_history (line_read);
    
  • 接下来就是返回指针,没啥好说了:

     return (line_read);
    

至此我们就已经完成了该函数的解释,这个文档也是由于ysyx计划的源码阅读要求而产生的,希望能帮助到后来者

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值