- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <limits.h> // necesar pentru PATH_MAX
- #define SECTOR_SIZE 4096
- void scrieFisier(char *map_addr, int length);
- void recursive(int f, int length, int offset, int PageSize);
- int main(int argc, char **argv)
- {
- if (argc < 2)
- {
- printf("Introdu numele fisierului.\n");
- exit(1);
- }
- for (int i = 1; i < argc; i++)
- if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
- {
- system("rev -h");
- exit(1);
- }
- for (int i = 1; i < argc; i++)
- if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0)
- {
- printf("1.0.0\n");
- exit(1);
- }
- for (int i = 1; i < argc; i++)
- {
- int f = open(argv[i], O_RDONLY);
- if (f == -1)
- {
- perror("A aparut o eroare cand am incercat sa deschide fisierul");
- continue;
- }
- long PageSize = sysconf(_SC_PAGE_SIZE);
- struct stat sb;
- if (PageSize == -1)
- {
- perror("Eroare la sysconf");
- exit(1);
- }
- if (fstat(f, &sb) == -1)
- {
- perror("Eroare la fstat");
- exit(2);
- }
- recursive(f, sb.st_size, 0, PageSize);
- }
- }
- void reverse(char *sir)
- {
- int lg = strlen(sir) - 1;
- for (int i = 0; i <= lg / 2; i++)
- {
- char aux = sir[i];
- sir[i] = sir[lg - i];
- sir[lg - i] = aux;
- }
- }
- void scrieFisier(char *map_addr, int length)
- {
- char aux[SECTOR_SIZE] = {0};
- for (int i = 0; i < length; i++)
- if (map_addr[i] != '\n')
- {
- int lg = strlen(aux);
- aux[lg] = map_addr[i];
- aux[lg + 1] = '\0';
- }
- else
- {
- reverse(aux);
- printf("%s\n", aux);
- aux[0] = '\0';
- }
- if (strlen(aux) > 0)
- {
- reverse(aux);
- printf("%s\n", aux);
- aux[0] = '\0';
- }
- }
- void recursive(int f, int length, int offset, int PageSize)
- {
- int ok = 0;
- char *map_addr;
- if (length > PageSize)
- {
- map_addr = mmap(NULL, PageSize, PROT_READ, MAP_PRIVATE, f, offset);
- scrieFisier(map_addr, PageSize);
- recursive(f, length - PageSize, offset + PageSize, PageSize);
- if (munmap(map_addr, PageSize) == -1)
- {
- perror("Erroare la munmap.");
- exit(4);
- }
- return;
- }
- map_addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, f, offset);
- scrieFisier(map_addr, length);
- if (munmap(map_addr, length) == -1)
- {
- perror("Erroare la munmap.");
- exit(4);
- }
- }