bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: readline fix


From: Simon Josefsson
Subject: Re: readline fix
Date: Thu, 10 Nov 2005 15:51:29 +0100
User-agent: Gnus/5.110004 (No Gnus v0.4) Emacs/22.0.50 (gnu/linux)

Eric Blake <address@hidden> writes:

> According to Simon Josefsson on 11/9/2005 7:17 PM:
>> Is this right?  I'm not sure what a portable way to remove EOL is.
>> Anyway, I installed this because it work on known platforms.
>
> The concept is correct (the full-blown readline library does indeed strip
> the trailing newline), but whether you should also strip \r is a different
> matter.

Some testing reveal that the readline strip any number of \n or \r at
the end:

address@hidden:~$ cat foo.c
#include <readline/readline.h>

int main () {
  char *foo = readline("bar: ");
  size_t i;

  for (i = 0; i < strlen (foo); i++)
    printf ("%02x\n", foo[i]);
}
address@hidden:~$ printf "f\r\r\n\r\n\n\r"|./foo
bar: 66
address@hidden:~$


>> +  if (out[strlen (out) - 1] == '\r')
>> +    out[strlen (out) - 1] = '\0';
>> +  if (out[strlen (out) - 1] == '\n')
>> +    out[strlen (out) - 1] = '\0';
>
> This is backwards: Windows text files have \r\n, so you should strip \n
> before \r if you are working from the end (and if others agree that
> stripping \r is the right thing to do).  Also, it ignores the fact that
> getline() can return embedded NULs, so that a) strlen() may be inaccurate,
> and b) it is a waste of computation since the return value of getline() is
> already the full length rather than walking the string multiple times.

We can't use the real size, because the readline interface doesn't
support embedded NULs.  We must strip any and all \n and \r before the
first NUL.

I installed the patch below.  What do you think?

--- readline.c  10 Nov 2005 15:41:49 +0100      1.3
+++ readline.c  10 Nov 2005 15:49:25 +0100      
@@ -48,9 +48,8 @@
   if (getline (&out, &size, stdin) < 0)
     return NULL;
 
-  if (out[strlen (out) - 1] == '\r')
-    out[strlen (out) - 1] = '\0';
-  if (out[strlen (out) - 1] == '\n')
+  while (*out && (out[strlen (out) - 1] == '\r'
+                 || out[strlen (out) - 1] == '\n'))
     out[strlen (out) - 1] = '\0';
 
   return out;




reply via email to

[Prev in Thread] Current Thread [Next in Thread]