[hackers] [sbase][PATCH] head: remove useless buffering

From: Elie Le Vaillant <eolien55_AT_disroot.org>
Date: Tue, 5 Mar 2024 18:53:00 +0100

getline isn't useful here, because we just need to read then output
lines. We do not need anything more complex than counting '\n's, so
we shouldn't use a buffer like we currently do.
---
 head.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
diff --git a/head.c b/head.c
index ae550c0..08a219b 100644
--- a/head.c
+++ b/head.c
_AT_@ -9,15 +9,16 @@
 static void
 head(FILE *fp, const char *fname, size_t n)
 {
-	char *buf = NULL;
-	size_t i = 0, size = 0;
-	ssize_t len;
+	int c;
+	size_t i = 0;
 
-	while (i < n && (len = getline(&buf, &size, fp)) > 0) {
-		fwrite(buf, 1, len, stdout);
-		i += (len && (buf[len - 1] == '\n'));
+	while (i < n && (c = fgetc(fp)) != EOF) {
+		if (fputc(c, stdout) == EOF)
+			eprintf("fputc:");
+		if (c == '\n')
+			i++;
 	}
-	free(buf);
+
 	if (ferror(fp))
 		eprintf("getline %s:", fname);
 }
-- 
2.44.0
Received on Tue Mar 05 2024 - 18:53:00 CET

This archive was generated by hypermail 2.3.0 : Tue Mar 05 2024 - 19:00:45 CET