Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- void all(const char *pattern, FILE *dictionary);
- void show_entries(char *pattern, FILE *stream);
- /* Вывод статей по заданному шаблону */
- char* filter_dictionary(char *hide_str, char *dictionary, char *buffer);
- /* Загрузка словаря в память */
- char* load_dictionary (char *dictionary, FILE *dict);
- #define MAXLINE 1023 /* Максимальный размер строки" */
- int main(int argc, char*argv[])
- {
- char *dictionary;
- char *buffer = NULL;
- dictionary = (char *) malloc(sizeof(char) * 1024 * 1024 * 10); /* Выделение динамической памяти для словаря */
- buffer = (char *) malloc(sizeof(char) * 1024 * 1024 * 10); /* Выделение памя ти для отобранных статей */
- /* Файл словаря */
- FILE* dict = NULL;
- /* Текущая строка */
- char current_line[MAXLINE + 1] = "";
- /* Номер искомой статьи */
- char requested_entry_number[MAXLINE + 1] = "";
- char hide_str[MAXLINE + 1] = "";
- /* Номер текущей словарной статьи */
- int current_entry_number = 0;
- /* Флаг соответствия текущей статьи условию отбора */
- int matched_entry = 0;
- /* Открываем файл и если файл словарной статьи не найден */
- if((dict = fopen(argv[1], "r")) == NULL)
- {
- printf("Файл словарной статьи не найден, не указан или не может быть открыт. \n"); /* ... то выводим сообщение об ошибке */
- return 0;
- }
- else {
- load_dictionary(dictionary, dict);
- do {
- buffer = (char*) calloc(1, sizeof(char) * 1024 * 1024 * 10);
- buffer = filter_dictionary(hide_str, dictionary, buffer);
- printf ("%s", buffer);
- free (buffer);
- }
- while (scanf("%s", hide_str) > 0);
- free (dictionary);
- return 0;
- }
- /*Считываем слово которое необходимо найти*/
- char pattern[MAXLINE];
- scanf("%s", pattern);
- show_entries(pattern, dict);
- /* Закончить работу со словарём */
- fclose(dict);
- return 0;
- }
- char *load_dictionary(char *dictionary, FILE * stream)
- {
- /* Загрузка файла в память */
- size_t resultate = fread(dictionary, 1, 10*1024*1024, stream);
- dictionary[resultate] = EOF;
- fclose(stream);
- return dictionary;
- }
- char* filter_dictionary(char *hide_str, char* dictionary, char* buffer)
- {
- int g = 0;
- int y = 0;
- int k = 0;
- int ch = 0;
- int f = 0;
- /* Находим размер введенной строки */
- while (hide_str[g])
- g++;
- /* Если первый символ ^ */
- if(hide_str[0] == '^') {
- g = g - 1;
- y = 1;
- for(int i = 0; i <= g; i++)
- hide_str[i] = hide_str[i + 1];
- }
- /* Если последний символ $ */
- if(hide_str[g-1] == '$') {
- hide_str[g-1] = '\0';
- g--;
- k = 1;
- }
- /* Текущая строка */
- char current_line[MAXLINE + 1] = "";
- int b = 0;
- int i = 0;
- int w = 0;
- /* Просматриваем словарь, печатая строки запрошенной статьи */
- while (dictionary[0] != EOF) {
- current_line[w] = dictionary[0];
- dictionary++;
- if (current_line[w] != '\n')
- {
- w++;
- continue;
- }
- else
- {
- current_line[w + 1] = '\0';
- w = 0;
- /* Если первый символ строки не является пробельным разделителем, на йдено начало новой словарной статьи */
- if (!isspace(current_line[0])) {
- i = 0;
- while (current_line[i] != '\0') {
- /* Определяем, выполнено ли условие отбора для данной строки */
- f = 0;
- ch = 0;
- int q = 0;
- if (current_line[i] == hide_str[q]) {
- while (current_line[i] == hide_str[q]) {
- i++;
- q++;
- }
- if (q == g) {
- b = 1;
- ch = i;
- if(current_line[ch + 1] == '\0') f = 1;
- break;
- } else{
- b = 0;
- f = 0;}
- } else
- i++;
- b = 0;
- f = 0;
- }
- }
- if (b && k == 0 && y == 0)
- strcat (buffer, current_line);
- if (b && k == 0 && y == 1 && ch == g)
- strcat (buffer, current_line);
- if (b && k == 1 && y == 0 && f)
- strcat (buffer, current_line);
- if (b && k == 1 && y == 1 && f && ch == g)
- strcat (buffer, current_line);
- }
- //q++;
- }
- return buffer;
- }
- void show_entries(char *pattern, FILE *stream){
- char ty[MAXLINE + 1];
- char current_line[MAXLINE + 1] = "";
- int matched_entry = 0;
- /*Если найдена ^ в начале строки или & в конце идем далее*/
- if(pattern[0] == '^' || pattern[strlen(pattern) - 1] == '$'){
- /*Если найдена и ^ и $ то выполняем следующее*/
- if(pattern[0] == '^' && pattern[strlen(pattern) - 1] == '$'){
- /*Копируем в пустую строчку слово которое мы ввели*/
- strncpy(ty, pattern, MAXLINE);
- /*Присваиваем значение последнего элемента терминального нуля*/
- ty[strlen(ty) - 1] = '\0';
- char ter[MAXLINE+1];
- char ter1[MAXLINE+1];
- /*Копируем в строку ter строку ty для дальнейшей обработки*/
- strncpy(ter, ty+1, MAXLINE);
- }
- else
- /*Если и ^ и $ отсутствует рассмотрим каждый вариант по отдельности* /
- {
- /*Если найдена только ^ в начале строки*/
- if(pattern[0] == '^') {
- strncpy(ty, pattern+1, MAXLINE);
- char ter[MAXLINE+1];
- /*Открываем цикл, в котором проверяем пока строка current_line н е будет заканчиваться*/
- while (fgets(current_line, MAXLINE, stream) != NULL) {
- /* Если первый символ строки не является пробельным разделит елем,
- найдено начало новой словарной статьи */
- /*посчитать длины строк, вычеcть из первой длины вторую, зап исать и обрезать в терминальный нуль*/
- if (isspace(current_line[0]) == 0) {
- int s1 = strlen(ty);
- int s2 = strlen(current_line);
- int s3 = s2 - s1;
- strncpy(ter, current_line, MAXLINE);
- ter[strlen(ter)-s3] = '\0';
- /*Если при сравнении ter и ty они окажутся одинаковыми т о ставим значение переменной matched_entry на 1, в другом случае 0*/
- if(strcmp(ter, ty) == 0)
- matched_entry = 1;
- else
- matched_entry = 0;
- }
- /* Печатаем строку, если она относится к запрошенной статье */
- if (matched_entry) {
- printf("%s", current_line);
- }
- }
- }
- else
- /*Если знак $ присутствует в конце строки */
- {
- strncpy(ty, pattern, MAXLINE);
- ty[strlen(ty) - 1] = '\0';
- char ter[MAXLINE+1];
- char ter1[MAXLINE+1];
- int k;
- while (fgets(current_line, MAXLINE, stream) != NULL) {
- /* Если первый символ строки не является пробельным разделит елем,
- найдено начало новой словарной статьи
- посчитать длины строк, вычестеть из первой длины вторую, записать и обрезать в терминальный нуль*/
- strncpy(ter1, current_line, MAXLINE);
- k = 0;
- while(ter1[k] != '\n')
- k++;
- // printf("%d\n", k);
- ter1[k] = '\0';
- if (isspace(current_line[0]) == 0) {
- int s1 = strlen(ty);
- int s2 = strlen(ter1);
- int s3 = s2 - s1;
- strncpy(ter, ter1+s3, MAXLINE);
- /*Если при сравнении ter и ty они окажутся одинаковыми
- то ставим значение переменной matched_entry на 1, в др угом случае 0*/
- if(strcmp(ter, ty) == 0){
- matched_entry = 1;
- }
- else
- {
- matched_entry = 0;
- }
- }
- /* Печатаем строку, если она относится к запрошенной статье */
- if (matched_entry) {
- printf("%s", current_line);
- }
- }
- }
- }
- }
- else
- {
- while (fgets(current_line, MAXLINE, stream) != NULL) {
- /* Если первый символ строки не является пробельным разделителем,
- найдено начало новой словарной статьи */
- if (!isspace(current_line[0])) {
- if(strstr(current_line, pattern))
- matched_entry = 1;
- else
- matched_entry = 0;
- }
- /* Печатаем строку, если она относится к запрошенной статье */
- if (matched_entry) {
- printf("%s", current_line);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement