Advertisement
STANAANDREY

solab4pb4

Mar 18th, 2024
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/stat.h>
  6. #include <limits.h>
  7. #include <string.h>
  8. #define MIN(a, b) ((a > b) ? b : a)
  9. #define MAX(a, b) ((a > b) ? a : b)
  10.  
  11. int getFD(const char *const fname, int flags, int perm) {
  12.   int fd = open(fname, flags, perm);
  13.   if (fd < 0) {
  14.     perror("");
  15.     exit(1);
  16.   }
  17.   return fd;
  18. }
  19.  
  20. void closeFD(int fd) {
  21.   if (close(fd) < 0) {
  22.     perror("");
  23.     exit(1);
  24.   }
  25. }
  26.  
  27. int main(int argc, char *argv[]) {
  28.  
  29.   if (argc != 3) {
  30.     fprintf(stderr, "Wrong usage!\n");
  31.     exit(1);
  32.   }
  33.  
  34.   int fd1 = getFD(argv[1], O_RDONLY, 0);
  35.  
  36.   unsigned sof;
  37.   unsigned on1b = 0, on2b = 0, on4b = 0;
  38.   unsigned min = UINT_MAX, max = 0;
  39.   unsigned long long sum = 0;
  40.   while (read(fd1, &sof, 1) > 0) {
  41.     unsigned len, data;
  42.     read(fd1, &len, 1);
  43.     read(fd1, &data, len);
  44.     switch (len) {
  45.     case 1:
  46.       on1b++;
  47.       break;
  48.     case 2:
  49.       on2b++;
  50.       break;
  51.     case 4:
  52.       on4b++;
  53.       break;
  54.     }
  55.     min = MIN(min, data);
  56.     max = MAX(max, data);
  57.     sum += data;
  58.   }
  59.   closeFD(fd1);
  60.  
  61.   int fd2 = getFD(argv[2], O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
  62.   static char ans[50];
  63.  
  64.   sprintf(ans, "min: %u\n", min);
  65.   write(fd2, ans, strlen(ans));
  66.   sprintf(ans, "max: %u\n", max);
  67.   write(fd2, ans, strlen(ans));
  68.   sprintf(ans, "avg: %g\n", 1. * sum / (on1b + on2b + on4b));
  69.   write(fd2, ans, strlen(ans));
  70.   sprintf(ans, "1 byte ints: %u\n", on1b);
  71.   write(fd2, ans, strlen(ans));
  72.   sprintf(ans, "2 byte ints: %u\n", on2b);
  73.   write(fd2, ans, strlen(ans));
  74.   sprintf(ans, "4 byte ints: %u\n", on4b);
  75.   write(fd2, ans, strlen(ans));
  76.  
  77.   close(fd2);
  78.   return 0;
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement