Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <malloc.h>
  6. #include <sys/stat.h>
  7. #include "mman.h"
  8.  
  9. int comparator(const void* a, const void* b)
  10. {
  11. const char* s1, * s2;
  12. s1 = *(char**)a;
  13. s2 = *(char**)b;
  14. int i = 0;
  15. while (s1[i] == s2[i] && s1[i] != '\n' && s2[i] != '\n')
  16. i++;
  17. return (s1[i] - s2[i]);
  18. }
  19.  
  20. int main()
  21. {
  22. int file_in = open("input.txt", O_RDWR, 0);
  23. FILE* file_out = fopen("output.txt", "w");
  24. if (file_in == -1 || file_out == NULL)
  25. {
  26. printf("Opening error\n");
  27. return 1;
  28. }
  29. struct stat data;
  30. fstat(file_in, &data);
  31. int size_file = data.st_size;
  32. char* text = mmap(0, size_file, PROT_READ, MAP_PRIVATE, file_in, 0);
  33. if (text == MAP_FAILED)
  34. {
  35. printf("Opening error\n");
  36. return 1;
  37. }
  38. int txtLen = strlen(text);
  39. int count_of_string = 0;
  40. for (int i = 0; i < txtLen; i++)
  41. if (text[i] == '\n')
  42. count_of_string++;
  43. count_of_string++;
  44. char **strings = (char**) malloc(count_of_string * sizeof(char*));
  45. if (strings == NULL)
  46. {
  47. printf("Memory allocation error\n");
  48. return 1;
  49. }
  50. int posStr = 0, posCur = 0;
  51. int i = 0;
  52. printf("Here1\n");
  53. while (text[i])
  54. {
  55. if (text[i] != '\n')
  56. {
  57. int j = i + 1;
  58. while (text[j] != '\n' && text[j] != '\0')
  59. j++;
  60. if (text[j] == '\0')
  61. j++;
  62. strings[posStr] = (char*)malloc((j - i - 1) * sizeof(char));
  63. printf("%d\n", posStr);
  64. for (int k = 0; k < j - i - 1; k++)
  65. strings[posStr][k] = text[i + k];
  66. strings[posStr][j - i - 1] = '\n';
  67. posStr++;
  68. i = j;
  69. }
  70. i++;
  71. }
  72. printf("Here2\n");
  73. qsort(strings, count_of_string, sizeof(char*), comparator);
  74. printf("Here3\n");
  75. for (i = 0; i < count_of_string ; i++)
  76. {
  77. size_t pos = 0;
  78. while (strings[i][pos] != '\n') {
  79. fputc(strings[i][pos], file_out);
  80. pos++;
  81. }
  82. fputc('\n', file_out);
  83. }
  84. printf("Here4\n");
  85. munmap(text, txtLen);
  86. for (i = 0; i < count_of_string; i++)
  87. free(strings[i]);
  88. free(strings);
  89. close(file_in);
  90. close(file_out);
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement