Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. void all(const char *pattern, FILE *dictionary);
  7.  
  8. void show_entries(char *pattern, FILE *stream);
  9. /* Вывод статей по заданному шаблону */
  10. char* filter_dictionary(char *hide_str, char *dictionary, char *buffer);
  11.  
  12. /* Загрузка словаря в память */
  13. char* load_dictionary (char *dictionary, FILE *dict);
  14.  
  15.  
  16. #define MAXLINE 1023 /* Максимальный размер строки" */
  17.  
  18. int main(int argc, char*argv[])
  19. {
  20. char *dictionary;
  21. char *buffer = NULL;
  22. dictionary = (char *) malloc(sizeof(char) * 1024 * 1024 * 10); /* Выделение динамической памяти для словаря */
  23. buffer = (char *) malloc(sizeof(char) * 1024 * 1024 * 10); /* Выделение памя ти для отобранных статей */
  24. /* Файл словаря */
  25. FILE* dict = NULL;
  26.  
  27. /* Текущая строка */
  28. char current_line[MAXLINE + 1] = "";
  29.  
  30. /* Номер искомой статьи */
  31. char requested_entry_number[MAXLINE + 1] = "";
  32.  
  33. char hide_str[MAXLINE + 1] = "";
  34.  
  35. /* Номер текущей словарной статьи */
  36. int current_entry_number = 0;
  37.  
  38. /* Флаг соответствия текущей статьи условию отбора */
  39. int matched_entry = 0;
  40.  
  41. /* Открываем файл и если файл словарной статьи не найден */
  42. if((dict = fopen(argv[1], "r")) == NULL)
  43. {
  44. printf("Файл словарной статьи не найден, не указан или не может быть открыт. \n"); /* ... то выводим сообщение об ошибке */
  45. return 0;
  46. }
  47. else {
  48.  
  49. load_dictionary(dictionary, dict);
  50.  
  51. do {
  52. buffer = (char*) calloc(1, sizeof(char) * 1024 * 1024 * 10);
  53. buffer = filter_dictionary(hide_str, dictionary, buffer);
  54. printf ("%s", buffer);
  55. free (buffer);
  56. }
  57. while (scanf("%s", hide_str) > 0);
  58.  
  59. free (dictionary);
  60. return 0;
  61. }
  62.  
  63. /*Считываем слово которое необходимо найти*/
  64. char pattern[MAXLINE];
  65. scanf("%s", pattern);
  66. show_entries(pattern, dict);
  67.  
  68.  
  69.  
  70. /* Закончить работу со словарём */
  71. fclose(dict);
  72. return 0;
  73. }
  74.  
  75. char *load_dictionary(char *dictionary, FILE * stream)
  76. {
  77. /* Загрузка файла в память */
  78. size_t resultate = fread(dictionary, 1, 10*1024*1024, stream);
  79. dictionary[resultate] = EOF;
  80. fclose(stream);
  81.  
  82. return dictionary;
  83. }
  84.  
  85.  
  86.  
  87. char* filter_dictionary(char *hide_str, char* dictionary, char* buffer)
  88. {
  89.  
  90. int g = 0;
  91. int y = 0;
  92. int k = 0;
  93. int ch = 0;
  94. int f = 0;
  95.  
  96.  
  97. /* Находим размер введенной строки */
  98. while (hide_str[g])
  99. g++;
  100.  
  101. /* Если первый символ ^ */
  102. if(hide_str[0] == '^') {
  103. g = g - 1;
  104. y = 1;
  105. for(int i = 0; i <= g; i++)
  106. hide_str[i] = hide_str[i + 1];
  107. }
  108.  
  109. /* Если последний символ $ */
  110. if(hide_str[g-1] == '$') {
  111. hide_str[g-1] = '\0';
  112. g--;
  113. k = 1;
  114. }
  115.  
  116. /* Текущая строка */
  117. char current_line[MAXLINE + 1] = "";
  118. int b = 0;
  119. int i = 0;
  120. int w = 0;
  121. /* Просматриваем словарь, печатая строки запрошенной статьи */
  122. while (dictionary[0] != EOF) {
  123. current_line[w] = dictionary[0];
  124. dictionary++;
  125. if (current_line[w] != '\n')
  126. {
  127. w++;
  128. continue;
  129. }
  130. else
  131. {
  132. current_line[w + 1] = '\0';
  133. w = 0;
  134.  
  135. /* Если первый символ строки не является пробельным разделителем, на йдено начало новой словарной статьи */
  136. if (!isspace(current_line[0])) {
  137. i = 0;
  138.  
  139. while (current_line[i] != '\0') {
  140. /* Определяем, выполнено ли условие отбора для данной строки */
  141. f = 0;
  142. ch = 0;
  143. int q = 0;
  144. if (current_line[i] == hide_str[q]) {
  145. while (current_line[i] == hide_str[q]) {
  146. i++;
  147. q++;
  148. }
  149. if (q == g) {
  150. b = 1;
  151. ch = i;
  152. if(current_line[ch + 1] == '\0') f = 1;
  153. break;
  154. } else{
  155. b = 0;
  156. f = 0;}
  157. } else
  158. i++;
  159.  
  160. b = 0;
  161. f = 0;
  162. }
  163. }
  164.  
  165. if (b && k == 0 && y == 0)
  166. strcat (buffer, current_line);
  167.  
  168. if (b && k == 0 && y == 1 && ch == g)
  169. strcat (buffer, current_line);
  170.  
  171. if (b && k == 1 && y == 0 && f)
  172. strcat (buffer, current_line);
  173.  
  174. if (b && k == 1 && y == 1 && f && ch == g)
  175. strcat (buffer, current_line);
  176.  
  177.  
  178. }
  179.  
  180. //q++;
  181.  
  182. }
  183.  
  184.  
  185. return buffer;
  186. }
  187.  
  188.  
  189. void show_entries(char *pattern, FILE *stream){
  190. char ty[MAXLINE + 1];
  191. char current_line[MAXLINE + 1] = "";
  192. int matched_entry = 0;
  193.  
  194.  
  195. /*Если найдена ^ в начале строки или & в конце идем далее*/
  196. if(pattern[0] == '^' || pattern[strlen(pattern) - 1] == '$'){
  197. /*Если найдена и ^ и $ то выполняем следующее*/
  198. if(pattern[0] == '^' && pattern[strlen(pattern) - 1] == '$'){
  199. /*Копируем в пустую строчку слово которое мы ввели*/
  200. strncpy(ty, pattern, MAXLINE);
  201. /*Присваиваем значение последнего элемента терминального нуля*/
  202. ty[strlen(ty) - 1] = '\0';
  203. char ter[MAXLINE+1];
  204. char ter1[MAXLINE+1];
  205. /*Копируем в строку ter строку ty для дальнейшей обработки*/
  206. strncpy(ter, ty+1, MAXLINE);
  207.  
  208. }
  209. else
  210. /*Если и ^ и $ отсутствует рассмотрим каждый вариант по отдельности* /
  211. {
  212. /*Если найдена только ^ в начале строки*/
  213. if(pattern[0] == '^') {
  214. strncpy(ty, pattern+1, MAXLINE);
  215. char ter[MAXLINE+1];
  216. /*Открываем цикл, в котором проверяем пока строка current_line н е будет заканчиваться*/
  217. while (fgets(current_line, MAXLINE, stream) != NULL) {
  218. /* Если первый символ строки не является пробельным разделит елем,
  219. найдено начало новой словарной статьи */
  220. /*посчитать длины строк, вычеcть из первой длины вторую, зап исать и обрезать в терминальный нуль*/
  221. if (isspace(current_line[0]) == 0) {
  222. int s1 = strlen(ty);
  223. int s2 = strlen(current_line);
  224. int s3 = s2 - s1;
  225. strncpy(ter, current_line, MAXLINE);
  226. ter[strlen(ter)-s3] = '\0';
  227. /*Если при сравнении ter и ty они окажутся одинаковыми т о ставим значение переменной matched_entry на 1, в другом случае 0*/
  228. if(strcmp(ter, ty) == 0)
  229. matched_entry = 1;
  230. else
  231. matched_entry = 0;
  232. }
  233. /* Печатаем строку, если она относится к запрошенной статье */
  234. if (matched_entry) {
  235. printf("%s", current_line);
  236. }
  237. }
  238. }
  239. else
  240. /*Если знак $ присутствует в конце строки */
  241. {
  242.  
  243. strncpy(ty, pattern, MAXLINE);
  244. ty[strlen(ty) - 1] = '\0';
  245. char ter[MAXLINE+1];
  246. char ter1[MAXLINE+1];
  247. int k;
  248. while (fgets(current_line, MAXLINE, stream) != NULL) {
  249. /* Если первый символ строки не является пробельным разделит елем,
  250. найдено начало новой словарной статьи
  251. посчитать длины строк, вычестеть из первой длины вторую, записать и обрезать в терминальный нуль*/
  252. strncpy(ter1, current_line, MAXLINE);
  253. k = 0;
  254. while(ter1[k] != '\n')
  255. k++;
  256. // printf("%d\n", k);
  257. ter1[k] = '\0';
  258. if (isspace(current_line[0]) == 0) {
  259.  
  260. int s1 = strlen(ty);
  261. int s2 = strlen(ter1);
  262. int s3 = s2 - s1;
  263. strncpy(ter, ter1+s3, MAXLINE);
  264. /*Если при сравнении ter и ty они окажутся одинаковыми
  265. то ставим значение переменной matched_entry на 1, в др угом случае 0*/
  266. if(strcmp(ter, ty) == 0){
  267. matched_entry = 1;
  268. }
  269. else
  270. {
  271. matched_entry = 0;
  272. }
  273. }
  274. /* Печатаем строку, если она относится к запрошенной статье */
  275. if (matched_entry) {
  276. printf("%s", current_line);
  277.  
  278. }
  279. }
  280. }
  281. }
  282. }
  283. else
  284. {
  285. while (fgets(current_line, MAXLINE, stream) != NULL) {
  286.  
  287.  
  288. /* Если первый символ строки не является пробельным разделителем,
  289. найдено начало новой словарной статьи */
  290. if (!isspace(current_line[0])) {
  291. if(strstr(current_line, pattern))
  292. matched_entry = 1;
  293. else
  294. matched_entry = 0;
  295. }
  296. /* Печатаем строку, если она относится к запрошенной статье */
  297. if (matched_entry) {
  298. printf("%s", current_line);
  299. }
  300. }
  301. }
  302. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement