Advertisement
Khody

Untitled

Mar 17th, 2022
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5.  
  6. ssize_t Max(ssize_t a, ssize_t b) {
  7.     return a > b ? a : b;
  8. }
  9.  
  10. ssize_t CatFile(int fd) {
  11.     char buf[4096];
  12.     ssize_t r;
  13.  
  14.     do {
  15.         r = read(fd, buf, 4096);
  16.         if (r < 0) {
  17.             dprintf(STDERR_FILENO, "there is something wrong with read\n");
  18.             return 0;
  19.         }
  20.  
  21.         ssize_t wr;
  22.         for (size_t i = 0; i < r; i += Max(wr, 0)) {
  23.             wr = write(STDOUT_FILENO, buf + i, r - i);
  24.             if (wr >= 0 || errno == EINTR || errno == EAGAIN) {
  25.                 continue;
  26.             }
  27.  
  28.             return 1;
  29.         }
  30.     } while (r != 0);
  31.  
  32.     return 0;
  33. }
  34.  
  35. int main(int argc, char *argv[]) {
  36.     if (argc == 1) {
  37.         return (int) CatFile(STDIN_FILENO);
  38.     }
  39.  
  40.     for (int i = 1; i < argc; ++i) {
  41.         int fd = open(argv[i], O_RDONLY);
  42.         if (fd < 0) {
  43.             if (errno == ENOENT) {
  44.                 dprintf(STDERR_FILENO, "there is something wrong with the file\n");
  45.                 continue;
  46.             }
  47.            
  48.             return 1;
  49.         }
  50.  
  51.         ssize_t cat_res = CatFile(fd);
  52.         close(fd);
  53.  
  54.         if (cat_res) {
  55.             return 1;
  56.         }
  57.     }
  58.  
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement