diff options
author | balatt <56897347+balatt@users.noreply.github.com> | 2019-10-29 11:08:09 -0400 |
---|---|---|
committer | Andreas Kling <awesomekling@gmail.com> | 2019-10-29 16:08:09 +0100 |
commit | 5442e365c9e9cbb43a4a86a71e92b52a1b4e8d81 (patch) | |
tree | e782f585af30ae9c7f5effa2c782fbadf7f50188 /Userland | |
parent | fa69b9fbb7232f54c928ec8466af77b00aa94bbc (diff) | |
download | serenity-5442e365c9e9cbb43a4a86a71e92b52a1b4e8d81.zip |
cat: Updated to handle multiple input files (#694)
Now concatenates multiple files at once with a for loop iterating
through a vector of file arguments.
Diffstat (limited to 'Userland')
-rw-r--r-- | Userland/cat.cpp | 48 |
1 files changed, 30 insertions, 18 deletions
diff --git a/Userland/cat.cpp b/Userland/cat.cpp index e03801487d..bfbcc110f1 100644 --- a/Userland/cat.cpp +++ b/Userland/cat.cpp @@ -1,3 +1,4 @@ +#include <AK/Vector.h> #include <assert.h> #include <errno.h> #include <fcntl.h> @@ -8,26 +9,37 @@ int main(int argc, char** argv) { - int fd = argc > 1 ? open(argv[1], O_RDONLY) : 0; - if (fd == -1) { - fprintf(stderr, "Failed to open %s: %s\n", argv[1], strerror(errno)); - return 1; - } - for (;;) { - char buf[4096]; - ssize_t nread = read(fd, buf, sizeof(buf)); - if (nread == 0) - break; - if (nread < 0) { - perror("read"); - return 2; + Vector<int> fds; + if (argc > 1) { + for (int i = 0; i < argc; i++) { + int fd; + if ((fd = open(argv[i], O_RDONLY)) == -1) { + fprintf(stderr, "Failed to open %s: %s\n", argv[i], strerror(errno)); + continue; + } + fds.append(fd); } - ssize_t nwritten = write(1, buf, nread); - if (nwritten < 0) { - perror("write"); - return 3; + } else { + fds.append(0); + } + for (auto& fd : fds) { + for (;;) { + char buf[4096]; + ssize_t nread = read(fd, buf, sizeof(buf)); + if (nread == 0) + break; + if (nread < 0) { + perror("read"); + return 2; + } + ssize_t nwritten = write(1, buf, nread); + if (nwritten < 0) { + perror("write"); + return 3; + } + ASSERT(nwritten == nread); } - ASSERT(nwritten == nread); + close(fd); } return 0; } |