Advertisement
blazinghorizon

Untitled

Nov 4th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.72 KB | None | 0 0
  1. /*
  2. * dict2.c -- программа поиска слов в словаре по шаблону
  3. *
  4. * Copyright (c) 2019, Nikita Semenov <ndsemeno@cs.karelia.ru>
  5. *
  6. * This code is licensed under a MIT-style license
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <ctype.h>
  13. #define MAXLINE 1023
  14.  
  15. char* load_dictionary(char *dictionary, FILE *stream);
  16.  
  17. char* filter_dictionary(const char *pattern, const char *dictionary, char *entries);
  18.  
  19. int main(int argc, char *argv[])
  20. {
  21. /* Файл словаря */
  22. FILE *dict = NULL;
  23.  
  24. /* Открываем файл словаря и проверяем успешность открытия */
  25. dict = fopen(argv[1], "r");
  26. if (dict == NULL) {
  27. fprintf(stderr, "Невозможно открыть файл \n");
  28. exit(EXIT_FAILURE);
  29. }
  30.  
  31. /* Создание буфера для загрузки файла */
  32. char *dictionary;
  33. dictionary = (char*) malloc(sizeof(char) * 10 * 1024 * 1024); // Выделение памяти 10 МБ
  34. load_dictionary(dictionary, dict); // Копирование файла в буфер
  35. if (dictionary == NULL) {
  36. fprintf(stderr, "Невозможно скопировать файл \n");
  37. exit(EXIT_FAILURE);
  38. }
  39. fclose(dict); // Файл больше не нужен
  40.  
  41. /* Создание буфера для хранения результата поиска */
  42. char *entries;
  43. entries = (char*) malloc(sizeof(char) * 10 * 1024 * 1024);
  44.  
  45. /* Считываем шаблон для поиска */
  46. char pattern[MAXLINE + 1] = "";
  47.  
  48. printf("Введите шаблон \n");
  49. scanf("%s", pattern);
  50. while (pattern[0] != '\0' ) {
  51. filter_dictionary(pattern, dictionary, entries);
  52. printf("%s", entries);
  53. memset(entries, '\0', 10*1024*1024);
  54. printf("Введите шаблон \n");
  55. memset(pattern, '\0', MAXLINE + 1);
  56. scanf("%s", pattern);
  57. }
  58. free(dictionary);
  59. free(entries);
  60. return 0;
  61. }
  62.  
  63. char* load_dictionary(char *dictionary, FILE *stream)
  64. {
  65. /* Счет кол-ва символов в файле */
  66. fseek(stream, 0, SEEK_END);
  67. long lSize = ftell(stream);
  68. rewind (stream);
  69.  
  70. /* Копирование файла в буфер */
  71. fread(dictionary, 1, lSize, stream);
  72.  
  73. /* Подсчет кол-ва символов в буфере */
  74. long dSize = strlen(dictionary);
  75.  
  76. /* Сравнение количеств символов, если в файле > чем в буфере -> памяти не хватило*/
  77. if (lSize != dSize)
  78. dictionary = NULL;
  79.  
  80. return 0;
  81. }
  82.  
  83. char* filter_dictionary(const char *pattern, const char *dictionary, char *entries)
  84. {
  85. /* Вычисляем длину шаблона */
  86. int len = strlen(pattern);
  87.  
  88. /* Проверка шаблона на модификатор */
  89.  
  90. int ptrn_mode = 0, tmp = 0, k = 0;
  91. int i = 0, j = 0, cnt = 0;
  92.  
  93. if (pattern[0] == '^') {
  94. ptrn_mode = 1;
  95. tmp = 1;
  96. } else {
  97. if ((pattern[len - 1] == '$') & (pattern[0] != '^')) {
  98. ptrn_mode = 2;
  99. tmp = 1;
  100. k = 1;
  101. } else {
  102. if ((pattern[0] == '^') & (pattern[len - 1] == '$')) {
  103. ptrn_mode = 3;
  104. tmp = 1;
  105. len--;
  106. }
  107. }
  108. }
  109. int nachalo = 0; int t = 0;
  110. while (dictionary[i] != 0) {
  111. /* Возвращение переменных к начальному значению */
  112. cnt = 0;
  113. j = tmp - k;
  114. /* Проверка на начало новой статьи */
  115. if (!isspace(dictionary[i])) {
  116. nachalo = i;
  117. /* Цикл идет пока i-ый символ строки не символ перевода строки или символ шаблона - $ */
  118. while ((dictionary[i] != '\n') & (pattern[j] != '$')) {
  119. /* Если соответствующие символы шаблона и строки одинаковы */
  120. if (dictionary[i++] == pattern[j]) {
  121. cnt++;
  122. j++;
  123. /* Проверка числа успешных совпадений и длины шаблона */
  124. if (cnt == (len - tmp)) {
  125. /* Действия при шаблонах */
  126. if ((ptrn_mode == 0) || ((ptrn_mode == 1) & ((i + 1) == len))
  127. || ((ptrn_mode == 2) & (dictionary[i] == '\n')) ||
  128. ((ptrn_mode == 3) & (dictionary[i] == '\n') & ((i + 1) == len))) {
  129. while (dictionary[i] != '\n') {
  130. i++;
  131. }
  132. while (nachalo < i) {
  133. entries[t] = dictionary[nachalo];
  134. nachalo++;
  135. t++;
  136. }
  137. entries[t++] = '\n';
  138. break;
  139. }
  140. }
  141. /* Если соответсвующие символы не равны */
  142. } else {
  143. /* Проверка на случай, при котором первая буква шаблона равна
  144. * i-ой букве строки, причем эти буквы повторяются
  145. */
  146. if (pattern[0] == dictionary[i - 1]) {
  147. cnt = 1;
  148. j++;
  149. } else {
  150. cnt = 0;
  151. j = tmp - k;
  152. }
  153. }
  154. }
  155. } else {
  156. /* Движение по буферу до начала новой статьи */
  157. while (dictionary[i] != '\n') {
  158. i++;
  159. }
  160. i++;
  161. }
  162. }
  163. return 0;
  164. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement