- #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
- char buffer[SECTOR_SIZE], comanda[10];
- int bytes_read;
- int main(int argc, char **argv)
- {
- struct stat sb;
- long PageSize = sysconf(_SC_PAGE_SIZE);
- if (PageSize == -1)
- {
- perror("Eroare la sysconf");
- exit(1);
- }
- if (argc < 4)
- {
- printf("Optiuni insuficiente.");
- exit(1);
- }
- int f1 = open(argv[1], O_RDONLY);
- if (f1 < 0)
- {
- perror("Error on opening file");
- exit(1);
- }
- int f2 = open(argv[3], O_RDWR);
- if (f2 > 0)
- {
- printf("Doriti sa suprascrieti continutul ? da/nu \n");
- scanf("%10s", &comanda);
- if (strcmp(comanda, "da") != 0)
- {
- printf("\nNu ai acordat permisiunea \n");
- exit(5);
- }
- }
- else
- {
- f2 = open(argv[3], O_RDWR | O_CREAT);
- chmod(argv[3], S_IRUSR | S_IWUSR);
- }
- if (fstat(f1, &sb) == -1)
- {
- perror("Eroare la fstat");
- exit(4);
- }
- int offset = 0;
- int length = sb.st_size;
- if (ftruncate(f2, length) == -1)
- {
- perror("Eroare la trunchiere");
- exit(5);
- }
- while (length > PageSize)
- {
- afiseaza(f1, f2, PageSize, offset, argv[2][0], argv[4][0]);
- length -= PageSize;
- offset += PageSize;
- }
- afiseaza(f1, f2, length, offset, argv[2][0], argv[4][0]);
- if (close(f1) == -1 || close(f2) == -1)
- {
- perror("Error on closing files");
- exit(9);
- }
- return 0;
- }
- void afiseaza(int f1, int f2, int length, int offset, char c1, char c2)
- {
- char *map_addr1 = mmap(NULL, length, PROT_READ, MAP_SHARED, f1, offset);
- char *map_addr2 = mmap(NULL, length, PROT_WRITE, MAP_SHARED, f2, offset);
- if (map_addr1 == MAP_FAILED || map_addr2 == MAP_FAILED)
- {
- perror("Eroare la mmap.");
- exit(3);
- }
- for (int i = 0; i < length; i++)
- if (map_addr1[i] == c1)
- map_addr2[offset+i] = c2;
- else
- map_addr2[offset+i] = map_addr1[i];
- if (-1 == msync(map_addr2, length, MS_SYNC))
- {
- perror("Erroar la msync");
- exit(1);
- }
- if (munmap(map_addr1, length) == -1 || munmap(map_addr2, length) == -1)
- {
- perror("Erroare la munmap.");
- exit(2);
- }
- }