Advertisement
STANAANDREY

solab4pb3

Mar 1st, 2024 (edited)
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <limits.h>
  6. #include <string.h>
  7. #define MAX(a, b) a > b ? a : b
  8. #define MIN(a, b) a < b ? a : b
  9.  
  10. int getFD(const char *const path, int flags, int perm) {
  11.   int fd = open(path, flags, perm);
  12.   if (fd < 0) {
  13.     perror("Open err: ");
  14.     exit(1);
  15.   }
  16.   return fd;
  17. }
  18.  
  19. void closeFD(int fd) {
  20.   if (close(fd) < 0) {
  21.     perror("Close err: ");
  22.     exit(1);
  23.   }
  24. }
  25.  
  26. int main(int argc, char *argv[]) {
  27.   if (argc != 3) {
  28.     fprintf(stderr, "Wrong usage!\n");
  29.     exit(1);
  30.   }
  31.  
  32.   int fd1 = getFD(argv[1], O_RDONLY, 0);
  33.  
  34.   int nr;
  35.   int max = INT_MIN, min = INT_MAX;
  36.   int cnt = 0, sum = 0;
  37.   while (read(fd1, &nr, sizeof(int)) > 0) {
  38.     min = MIN(min, nr);
  39.     max = MAX(max, nr);
  40.     sum += nr;
  41.     cnt++;
  42.   }
  43.  
  44.   int fd2 = getFD(argv[2], O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
  45.  
  46.   char template[50] = "";
  47.   sprintf(template, " Min: %d\n Max: %d\n Mean: %lf\n", min, max, 1.0 * sum/cnt);
  48.   size_t templateLen = strlen(template);
  49.   if (write(fd2, template, templateLen) == -1) {
  50.     perror("Write err: ");
  51.     exit(1);
  52.   }
  53.    
  54.   closeFD(fd1);
  55.   closeFD(fd2);
  56.   return 0;
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement