From ef35b890c16c9f2d3aff29ce8562a3323aeb3a43 Mon Sep 17 00:00:00 2001 From: Aki Date: Thu, 16 Jun 2022 22:48:07 +0200 Subject: Streamlined error handling in head --- head.c | 62 +++++++++++++++++++++++++++----------------------------------- 1 file changed, 27 insertions(+), 35 deletions(-) diff --git a/head.c b/head.c index d5165e4..f4deca2 100644 --- a/head.c +++ b/head.c @@ -5,16 +5,14 @@ #include -int head(int fd, int lines, const char * name) +int head(const int fd, int lines) { static const size_t SIZE = 1024 * 4; char buffer[SIZE]; - while (lines > 0) { + while (0 < lines) { const ssize_t available = read(fd, buffer, SIZE); - if (-1 == available) { - perror(name); + if (-1 == available) return 1; - } if (0 == available) return 0; size_t offset = 0; @@ -22,11 +20,9 @@ int head(int fd, int lines, const char * name) if (buffer[n] == '\n') { lines--; if (0 <= lines) { - const ssize_t res = write(1, buffer + offset, 1 + n - offset); - if (-1 == res) { - perror(name); + const ssize_t result = write(1, buffer + offset, 1 + n - offset); + if (-1 == result) return 1; - } offset = 1 + n; } if (0 >= lines) @@ -34,11 +30,9 @@ int head(int fd, int lines, const char * name) } } if (0 < lines) { - const ssize_t res = write(1, buffer + offset, available - offset); - if (-1 == res) { - perror(name); + const ssize_t result = write(1, buffer + offset, available - offset); + if (-1 == result) return 1; - } } } return 0; @@ -49,7 +43,7 @@ int main(int argc, char * argv[]) { int opt; int lines = 10; - while (-1 != (opt = getopt(argc, argv, "n:"))) { + while (-1 != (opt=getopt(argc, argv, "n:"))) { switch (opt) { case 'n': errno = 0; @@ -66,28 +60,26 @@ int main(int argc, char * argv[]) return 1; } } - const unsigned int file_count = argc - optind; - int res = 0; - if (optind >= argc) - res |= head(0, lines, "-"); - else for (int i = optind; i < argc; ++i) { - if (1 < file_count) - printf("==> %s <==\n", argv[i]); - const unsigned int is_stdin = '-' == argv[i][0] && 0 == argv[i][1]; - const int fd = is_stdin ? 0 : open(argv[i], O_RDONLY); - if (-1 == fd) { - perror(argv[i]); - res = 1; - continue; + const int files_count = argc - optind; + int i = optind; + int overall = 0; + do { + const char * const path = argc == i ? "-" : argv[i]; + const unsigned int is_stdin = '-' == path[0] && 0 == path[1]; + const int fd = is_stdin ? 0 : open(path, O_RDONLY); + if (1 < files_count) + printf(optind == i ? "==> %s <==\n" : "\n==> %s <==\n", path); + if (0 <= fd) { + const int result = head(fd, lines) | is_stdin ? 0 : close(fd); + if (0 != result) + perror(path); + overall |= result; } - res |= head(fd, lines, argv[i]); - if (!is_stdin) { - const int clr = close(fd); - if (-1 == clr) { - perror(argv[i]); - res = 1; - } + else { + perror(path); + overall = 1; } } - return res; + while (++i < argc); + return overall; } -- cgit v1.1