Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <errno.h>
- ssize_t Max(ssize_t a, ssize_t b) {
- return a > b ? a : b;
- }
- ssize_t CatFile(int fd) {
- char buf[4096];
- ssize_t r;
- do {
- r = read(fd, buf, 4096);
- if (r < 0) {
- dprintf(STDERR_FILENO, "there is something wrong with read\n");
- return 0;
- }
- ssize_t wr;
- for (size_t i = 0; i < r; i += Max(wr, 0)) {
- wr = write(STDOUT_FILENO, buf + i, r - i);
- if (wr >= 0 || errno == EINTR || errno == EAGAIN) {
- continue;
- }
- return 1;
- }
- } while (r != 0);
- return 0;
- }
- int main(int argc, char *argv[]) {
- if (argc == 1) {
- return (int) CatFile(STDIN_FILENO);
- }
- for (int i = 1; i < argc; ++i) {
- int fd = open(argv[i], O_RDONLY);
- if (fd < 0) {
- if (errno == ENOENT) {
- dprintf(STDERR_FILENO, "there is something wrong with the file\n");
- continue;
- }
- return 1;
- }
- ssize_t cat_res = CatFile(fd);
- close(fd);
- if (cat_res) {
- return 1;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement