Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 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.  
  7. enum
  8. {
  9.     RIGHTS = 0666,
  10. };
  11.  
  12. void
  13. write_le(int fd, int val)
  14. {
  15.     char tmp[sizeof(val)];
  16.     unsigned mask = (1 << CHAR_BIT) - 1;
  17.     for (int i = 0; i < sizeof(val); ++i) {
  18.         tmp[i] = val & mask;
  19.         val >>= CHAR_BIT;
  20.     }
  21.     write(fd, tmp, sizeof(tmp));
  22. }
  23.  
  24.  
  25. void
  26. write_be(int fd, int val)
  27. {
  28.     char tmp[sizeof(val)];
  29.     unsigned mask = (1 << CHAR_BIT) - 1;
  30.     for (int i = sizeof(val) - 1; i >= 0; --i) {
  31.         tmp[i] = val & mask;
  32.         val >>= CHAR_BIT;
  33.     }
  34.     write(fd, tmp, sizeof(tmp));
  35. }
  36.  
  37. int
  38. main(int argc, char **argv)
  39. {
  40.     int fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, RIGHTS);
  41.  
  42.     switch (argv[2][0]) {
  43.     case 'L':
  44.         for (int i = 1; i < 11; ++i) {
  45.             write_le(fd, i);
  46.         }
  47.         break;
  48.     case 'B':
  49.         for (int i = 1; i < 11; ++i) {
  50.             write_be(fd, i);
  51.         }
  52.         break;
  53.     default:
  54.         for (int i = 1; i < 11; ++i) {
  55.             write(fd, &i, sizeof(i));
  56.         }
  57.     }
  58.  
  59.     close(fd);
  60.  
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement