diff --git a/utils/cat.cpp b/utils/cat.cpp index e941a274..8722535e 100644 --- a/utils/cat.cpp +++ b/utils/cat.cpp @@ -5,10 +5,27 @@ #include #include +bool writeall(int fd, const void* buffer, size_t len) +{ + const char* buf = (const char*) buffer; + while ( len ) + { + ssize_t byteswritten = write(fd, buf, len); + if ( byteswritten < 0 ) { return false; } + buf += byteswritten; + len -= byteswritten; + } + + return true; +} + int cat(int argc, char* argv[]) { int result = 0; + int outfd = open("/dev/tty", O_WRONLY | O_APPEND); + if ( outfd < 0 ) { printf("%s: %s: %s\n", argv[0], "/dev/tty", strerror(errno)); return 1; } + for ( int i = 1; i < argc; i++ ) { int fd = open(argv[i], O_RDONLY); @@ -31,8 +48,12 @@ int cat(int argc, char* argv[]) result = 1; break; } - buffer[bytesread] = 0; - printf("%s", buffer); + if ( !writeall(outfd, buffer, bytesread) ) + { + printf("%s: /dev/tty: %s\n", argv[0], strerror(errno)); + result = 1; + break; + } } while ( true ); close(fd);