1
0
mirror of https://github.com/openbsd/src.git synced 2025-01-10 06:47:55 -08:00

convert fgetln to getline. this improves portability and sets a good

better example for other code to follow. in the common case, grep uses
mmap anyway (so no functional change). despite fgetln doing sneaky things
with stdio internals, preliminary analysis by lauri suggests this may
actually reduce the number of allocations.
from Lauri Tirkkonen.
This commit is contained in:
tedu 2019-01-31 01:30:46 +00:00
parent fe56b6ec41
commit 6ec3986fe5
2 changed files with 19 additions and 11 deletions

View File

@ -1,4 +1,4 @@
/* $OpenBSD: file.c,v 1.14 2019/01/23 23:00:54 tedu Exp $ */
/* $OpenBSD: file.c,v 1.15 2019/01/31 01:30:46 tedu Exp $ */
/*-
* Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
@ -37,10 +37,8 @@
#include "grep.h"
static char fname[PATH_MAX];
#ifndef NOZ
static char *lnbuf;
static size_t lnbuflen;
#endif
static size_t lnbufsize;
#define FILE_STDIO 0
#define FILE_MMAP 1
@ -76,9 +74,9 @@ gzfgetln(gzFile *f, size_t *len)
else
errx(2, "%s: %s", fname, gzerrstr);
}
if (n >= lnbuflen) {
lnbuflen *= 2;
lnbuf = grep_realloc(lnbuf, ++lnbuflen);
if (n >= lnbufsize) {
lnbufsize *= 2;
lnbuf = grep_realloc(lnbuf, ++lnbufsize);
}
if (c == '\n')
break;
@ -181,7 +179,13 @@ grep_fgetln(file_t *f, size_t *l)
{
switch (f->type) {
case FILE_STDIO:
return fgetln(f->f, l);
if ((*l = getline(&lnbuf, &lnbufsize, f->f)) == -1) {
if (ferror(f->f))
err(2, "%s: getline", fname);
else
return NULL;
}
return lnbuf;
#ifndef SMALL
case FILE_MMAP:
return mmfgetln(f->mmf, l);

View File

@ -1,4 +1,4 @@
/* $OpenBSD: grep.c,v 1.58 2019/01/23 23:00:54 tedu Exp $ */
/* $OpenBSD: grep.c,v 1.59 2019/01/31 01:30:46 tedu Exp $ */
/*-
* Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
@ -222,15 +222,19 @@ read_patterns(const char *fn)
{
FILE *f;
char *line;
size_t len;
ssize_t len;
size_t linesize;
if ((f = fopen(fn, "r")) == NULL)
err(2, "%s", fn);
while ((line = fgetln(f, &len)) != NULL)
line = NULL;
linesize = 0;
while ((len = getline(&line, &linesize, f)) != -1)
add_pattern(line, *line == '\n' ? 0 : len);
if (ferror(f))
err(2, "%s", fn);
fclose(f);
free(line);
}
int