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().
This commit is contained in:
Andreas Kling 2019-06-06 10:40:12 +02:00
parent fe380d8f49
commit 6fa727a88e
Notes: sideshowbarker 2024-07-19 13:43:53 +09:00

View file

@ -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;
}