STANAANDREY

so2 lab1 pb1

Oct 30th, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <ctype.h>
  8. #include <string.h>
  9.  
  10. #define BLOCK_SIZE (1 << 12)
  11. #define AUX_SIZE 50
  12.  
  13. int openFile(const char path[], int flags, mode_t mode) {
  14.     int fd = open(path, flags, mode);
  15.     if (fd < 0) {
  16.         perror("");
  17.         exit(-1);
  18.     }
  19.     return fd;
  20. }
  21.  
  22. void closeFile(int fd) {
  23.     if (close(fd) == -1) {
  24.         perror("");
  25.         exit(-2);
  26.     }
  27. }
  28.  
  29. int getLowerCount(int n, const char buff[]) {
  30.     int cnt = 0;
  31.     for (int i = 0; i < n; i++) {
  32.         if (islower(buff[i])) {
  33.             cnt++;
  34.         }
  35.     }
  36.     return cnt;
  37. }
  38.  
  39. int main(int argc, char *argv[]) {
  40.     if (argc != 3) {
  41.         fprintf(stderr, "Wrong usage!\n");
  42.         exit(-1);
  43.     }
  44.     int fdin = openFile(argv[1], O_RDONLY, 0);
  45.     int fdout = openFile(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
  46.  
  47.     char buff[BLOCK_SIZE];
  48.     int cntLower = 0, readed;
  49.     while ((readed = read(fdin, buff, BLOCK_SIZE)) > 0) {
  50.         cntLower += getLowerCount(readed, buff);
  51.         char aux[AUX_SIZE] = {};
  52.         for (int i = 0; i < readed; i++) {
  53.             if (buff[i] >= 97 && buff[i] <= 122) {
  54.                 snprintf(aux, AUX_SIZE, "%c", buff[i]);
  55.             } else {
  56.                 snprintf(aux, AUX_SIZE, "(%02X)", buff[i]);
  57.             }
  58.             if (write(fdout, aux, strlen(aux)) == -1) {
  59.                 perror("");
  60.                 exit(-3);
  61.             }
  62.         }
  63.     }
  64.     if (write(fdout, "\n", 1) == -1) {
  65.         perror("");
  66.         exit(-3);
  67.     }
  68.     {
  69.         char aux[AUX_SIZE];
  70.         snprintf(aux, AUX_SIZE, "Lower letters: %d\n", cntLower);
  71.         if (write(fdout, aux, strlen(aux)) == -1) {
  72.             perror("");
  73.             exit(-3);
  74.         }
  75.     }
  76.    
  77.     closeFile(fdin);
  78.     closeFile(fdout);
  79.     return 0;
  80. }//dd if=/dev/urandom of=in.txt bs=1000 count=100
Add Comment
Please, Sign In to add comment