Re: sed: make use of getline(3)

2021-01-30 Thread Todd C . Miller
On Sat, 30 Jan 2021 00:43:02 +0100, Christian Weisgerber wrote:

> Replace fgetln(3) with getline(3) in sed.
>
> The mf_fgets() part is from Johann Oskarsson for Illumos/FreeBSD.
>
> Passes our sed regression tests.

OK millert@

 - todd



sed: make use of getline(3)

2021-01-29 Thread Christian Weisgerber
Replace fgetln(3) with getline(3) in sed.

The mf_fgets() part is from Johann Oskarsson for Illumos/FreeBSD.

Passes our sed regression tests.

OK?

Index: usr.bin/sed/main.c
===
RCS file: /cvs/src/usr.bin/sed/main.c,v
retrieving revision 1.41
diff -u -p -r1.41 main.c
--- usr.bin/sed/main.c  13 Oct 2020 06:07:54 -  1.41
+++ usr.bin/sed/main.c  29 Jan 2021 23:12:23 -
@@ -252,15 +252,9 @@ again:
goto again;
}
case ST_FILE:
-   if ((p = fgetln(f, &len)) != NULL) {
+   if (getline(outbuf, outsize, f) != -1) {
+   p = *outbuf;
linenum++;
-   if (len >= *outsize) {
-   free(*outbuf);
-   *outsize = ROUNDLEN(len + 1);
-   *outbuf = xmalloc(*outsize);
-   }
-   memcpy(*outbuf, p, len);
-   (*outbuf)[len] = '\0';
if (linenum == 1 && p[0] == '#' && p[1] == 'n')
nflag = 1;
return (*outbuf);
@@ -344,7 +338,8 @@ mf_fgets(SPACE *sp, enum e_spflag spflag
struct stat sb;
size_t len;
char dirbuf[PATH_MAX];
-   char *p;
+   static char *p;
+   static size_t psize;
int c, fd;
static int firstfile;
 
@@ -429,13 +424,13 @@ mf_fgets(SPACE *sp, enum e_spflag spflag
 * We are here only when infile is open and we still have something
 * to read from it.
 *
-* Use fgetln so that we can handle essentially infinite input data.
-* Can't use the pointer into the stdio buffer as the process space
-* because the ungetc() can cause it to move.
+* Use getline() so that we can handle essentially infinite input
+* data.  The p and psize are static so each invocation gives
+* getline() the same buffer which is expanded as needed.
 */
-   p = fgetln(infile, &len);
-   if (ferror(infile))
-   error(FATAL, "%s: %s", fname, strerror(errno ? errno : EIO));
+   len = getline(&p, &psize, infile);
+   if ((ssize_t)len == -1)
+   error(FATAL, "%s: %s", fname, strerror(errno));
if (len != 0 && p[len - 1] == '\n') {
sp->append_newline = 1;
len--;
-- 
Christian "naddy" Weisgerber  na...@mips.inka.de