commit 83182aa959b2100ea0cf6766e6ef3a553877a710
Author:     Elie Le Vaillant <eolie...@disroot.org>
AuthorDate: Fri Dec 6 10:37:44 2024 +0100
Commit:     Roberto E. Vargas Caballero <k...@shike2.com>
CommitDate: Thu Dec 19 11:58:49 2024 +0100

    head: remove useless buffering
    
    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.

diff --git a/head.c b/head.c
index ae550c0..230ad21 100644
--- a/head.c
+++ b/head.c
@@ -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 (putchar(c) == EOF)
+                       eprintf("fputc:");
+               if (c == '\n')
+                       i++;
        }
-       free(buf);
+
        if (ferror(fp))
                eprintf("getline %s:", fname);
 }

Reply via email to