Facebook
From Vlad, 4 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 125
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #include <unistd.h>
  6. #include <sys/mman.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. #include <limits.h> // necesar pentru PATH_MAX
  11.  
  12. #define SECTOR_SIZE 4096
  13.  
  14. void reverse(char *sir)
  15. {
  16.     int lg = strlen(sir) - 1;
  17.     for (int i = 0; i <= lg / 2; i++)
  18.     {
  19.         char aux = sir[i];
  20.         sir[i] = sir[lg - i];
  21.         sir[lg - i] = aux;
  22.     }
  23. }
  24.  
  25. void afiseaza(char *map_addr, int length)
  26. {
  27.     char aux[SECTOR_SIZE] = {0};
  28.     for (int i = length - 1; i >= 0; i--)
  29.         if (map_addr[i] != '\n')
  30.         {
  31.             int lg = strlen(aux);
  32.             aux[lg++] = map_addr[i];
  33.             aux[lg] = '\0';
  34.         }
  35.         else
  36.         {
  37.             if (strlen(aux) > 0)
  38.             {
  39.                 reverse(aux);
  40.                 printf("%s\n", aux);
  41.             }
  42.             aux[0] = '\0';
  43.         }
  44.     if (strlen(aux) > 0)
  45.     {
  46.         reverse(aux);
  47.         printf("%s\n", aux);
  48.     }
  49. }
  50.  
  51. void recursive(int f, int length, int offset, int PageSize)
  52. {
  53.     int ok = 0;
  54.     if (length > PageSize)
  55.     {
  56.         recursive(f, length - PageSize, offset + PageSize, PageSize);
  57.         ok = 1;
  58.     }
  59.     if (ok == 1)
  60.         length = PageSize;
  61.     char *map_addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, f, offset);
  62.     afiseaza(map_addr, length);
  63.     if (munmap(map_addr, length) == -1)
  64.     {
  65.         perror("Erroare la munmap.");
  66.         exit(4);
  67.     }
  68. }
  69.  
  70. void scrieFisier(char *numeFisier)
  71. {
  72.     int f = open(numeFisier, O_RDONLY);
  73.  
  74.     if (f == -1)
  75.     {
  76.         perror("A aparut o eroare cand am incercat sa deschide fisierul");
  77.         exit(2);
  78.     }
  79.  
  80.     long PageSize = sysconf(_SC_PAGE_SIZE);
  81.     struct stat sb;
  82.  
  83.     if (PageSize == -1)
  84.     {
  85.         perror("Eroare la sysconf");
  86.         exit(1);
  87.     }
  88.  
  89.     if (fstat(f, &sb) == -1)
  90.     {
  91.         perror("Eroare la fstat");
  92.         exit(2);
  93.     }
  94.  
  95.     recursive(f, sb.st_size, 0, PageSize);
  96. }
  97.  
  98. int main(int argc, char **argv)
  99. {
  100.     if (argc < 2)
  101.     {
  102.         printf("Introdu numele unui sau mai multor fisiere.");
  103.         exit(1);
  104.     }
  105.  
  106.     for (int i = 1; i < argc; i++)
  107.         scrieFisier(argv[i]);
  108.     printf("\n");
  109. }
  110.