From 6fa727a88ea75a2155996d16d721b5489c2c9085 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Thu, 6 Jun 2019 10:40:12 +0200 Subject: [PATCH] cat: Fix some oversights in error handling. Error messages should go to stderr so they don't get mixed in with the program's output. Also added a check for the return value of write(). --- Userland/cat.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Userland/cat.cpp b/Userland/cat.cpp index d084b532ed9..4b86ea9a14e 100644 --- a/Userland/cat.cpp +++ b/Userland/cat.cpp @@ -10,7 +10,7 @@ int main(int argc, char** argv) { int fd = argc > 1 ? open(argv[1], O_RDONLY) : 0; if (fd == -1) { - printf("failed to open %s: %s\n", argv[1], strerror(errno)); + fprintf(stderr, "Failed to open %s: %s\n", argv[1], strerror(errno)); return 1; } for (;;) { @@ -19,10 +19,15 @@ int main(int argc, char** argv) if (nread == 0) break; if (nread < 0) { - printf("read() error: %s\n", strerror(errno)); + perror("read"); return 2; } - write(1, buf, nread); + ssize_t nwritten = write(1, buf, nread); + if (nwritten < 0) { + perror("write"); + return 3; + } + ASSERT(nwritten == nread); } return 0; }