logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git
commit: 1dbb6e53be5452d9901879d96b611bafabec550f
parent 8ee8d7b92bfdda109c83d24151c468a487ab0a8d
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Fri, 27 Sep 2024 10:18:32 +0200

cmd/head: use auto_fd_copy

Diffstat:

MMakefile4++--
Mcmd/head.c49++++++++-----------------------------------------
2 files changed, 10 insertions(+), 43 deletions(-)

diff --git a/Makefile b/Makefile @@ -154,9 +154,9 @@ cmd/truncate: cmd/truncate.c lib/truncation.c lib/truncation.h Makefile $(RM) -f ${<:=.gcov} ${@:=.gcda} ${@:=.gcno} $(CC) -std=c99 $(CFLAGS) -o $@ cmd/truncate.c lib/truncation.c $(LDFLAGS) $(LDSTATIC) -cmd/head: cmd/head.c lib/truncation.c lib/truncation.h Makefile +cmd/head: cmd/head.c lib/truncation.c lib/truncation.h lib/fs.c lib/fs.h Makefile $(RM) -f ${<:=.gcov} ${@:=.gcda} ${@:=.gcno} - $(CC) -std=c99 $(CFLAGS) -o $@ cmd/head.c lib/truncation.c $(LDFLAGS) $(LDSTATIC) + $(CC) -std=c99 $(CFLAGS) -o $@ cmd/head.c lib/truncation.c lib/fs.c $(LDFLAGS) $(LDSTATIC) cmd/split: cmd/split.c lib/truncation.c lib/truncation.h lib/fs.c lib/fs.h Makefile $(RM) -f ${<:=.gcov} ${@:=.gcda} ${@:=.gcno} diff --git a/cmd/head.c b/cmd/head.c @@ -4,6 +4,7 @@ #define _POSIX_C_SOURCE 200809L +#include "../lib/fs.h" // auto_fd_copy #include "../lib/truncation.h" // apply_size_suffix #include <assert.h> @@ -15,8 +16,6 @@ #include <string.h> // strerror #include <unistd.h> // read -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) - static const char *header_fmt = "==> %s <==\n"; const char *argv0 = "head"; @@ -32,20 +31,6 @@ int delim = '\n'; static int copy_bytes(const char *filename) { - if(buflen == 0) - { - // Note: de-allocated in main() - buf = malloc(BUFSIZ); - - if(buf == NULL) - { - fprintf(stderr, "%s: error: Failed to allocate buffer: %s\n", argv0, strerror(errno)); - return 1; - } - - buflen = BUFSIZ; - } - int fd = -1; if(filename[0] == '-' && filename[1] == 0) { @@ -63,32 +48,14 @@ copy_bytes(const char *filename) } int err = 0; - - for(size_t i = 0; i < bytes;) + if(auto_fd_copy(fd, STDOUT_FILENO, bytes) < 0) { - ssize_t nread = read(fd, buf, MIN(buflen, bytes - i)); - if(nread < 0) - { - fprintf( - stderr, "%s: error: Failed reading file '%s': %s\n", argv0, filename, strerror(errno)); - err = 1; - break; - } - - if(nread == 0) break; - - if(write(STDOUT_FILENO, buf, nread) < 0) - { - fprintf(stderr, - "%s: error: Failed writing line from '%s' to stdout: %s\n", - argv0, - filename, - strerror(errno)); - err = 1; - break; - } - - i += nread; + fprintf(stderr, + "%s: error: Failed copying data from '%s' to <stdout>: %s\n", + argv0, + filename, + strerror(errno)); + err = 1; } if(fd != STDIN_FILENO)