Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <fcntl.h>
- #include <malloc.h>
- #include <sys/stat.h>
- #include "mman.h"
- int comparator(const void* a, const void* b)
- {
- const char* s1, * s2;
- s1 = *(char**)a;
- s2 = *(char**)b;
- int i = 0;
- while (s1[i] == s2[i] && s1[i] != '\n' && s2[i] != '\n')
- i++;
- return (s1[i] - s2[i]);
- }
- int main()
- {
- int file_in = open("input.txt", O_RDWR, 0);
- FILE* file_out = fopen("output.txt", "w");
- if (file_in == -1 || file_out == NULL)
- {
- printf("Opening error\n");
- return 1;
- }
- struct stat data;
- fstat(file_in, &data);
- int size_file = data.st_size;
- char* text = mmap(0, size_file, PROT_READ, MAP_PRIVATE, file_in, 0);
- if (text == MAP_FAILED)
- {
- printf("Opening error\n");
- return 1;
- }
- int txtLen = strlen(text);
- int count_of_string = 0;
- for (int i = 0; i < txtLen; i++)
- if (text[i] == '\n')
- count_of_string++;
- count_of_string++;
- char **strings = (char**) malloc(count_of_string * sizeof(char*));
- if (strings == NULL)
- {
- printf("Memory allocation error\n");
- return 1;
- }
- int posStr = 0, posCur = 0;
- int i = 0;
- printf("Here1\n");
- while (text[i])
- {
- if (text[i] != '\n')
- {
- int j = i + 1;
- while (text[j] != '\n' && text[j] != '\0')
- j++;
- if (text[j] == '\0')
- j++;
- strings[posStr] = (char*)malloc((j - i - 1) * sizeof(char));
- printf("%d\n", posStr);
- for (int k = 0; k < j - i - 1; k++)
- strings[posStr][k] = text[i + k];
- strings[posStr][j - i - 1] = '\n';
- posStr++;
- i = j;
- }
- i++;
- }
- printf("Here2\n");
- qsort(strings, count_of_string, sizeof(char*), comparator);
- printf("Here3\n");
- for (i = 0; i < count_of_string ; i++)
- {
- size_t pos = 0;
- while (strings[i][pos] != '\n') {
- fputc(strings[i][pos], file_out);
- pos++;
- }
- fputc('\n', file_out);
- }
- printf("Here4\n");
- munmap(text, txtLen);
- for (i = 0; i < count_of_string; i++)
- free(strings[i]);
- free(strings);
- close(file_in);
- close(file_out);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement