Advertisement
CherMi

Lab3

Feb 27th, 2020
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 8.52 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <malloc.h>
  4. #include <string.h>
  5.  
  6. void create_queue(struct descriptor *descriptor); //Подпрограмма создания очереди
  7. void output_queue(struct descriptor *descriptor); //Подпрограмма вывода очереди на экран или в файл
  8. void add_element(struct descriptor *descriptor); //Подпрограмма добавления элемента в очередь
  9. void delete_element(struct descriptor *descriptor); //Подпрограмма выборки элемента из очереди
  10. void clear_queue(struct descriptor *descriptor); //Подпрограмма очистки очереди
  11.  
  12. struct queue_element //Элемент очереди
  13. {
  14.     char *data;
  15.     struct queue_element *next;
  16. };
  17. struct descriptor //Дескриптор очереди
  18. {
  19.     struct queue_element *head;
  20.     struct queue_element *tail;
  21.     int exists;
  22. };
  23.  
  24. void main()
  25. {
  26.     struct descriptor descriptor;
  27.     int key;
  28.  
  29.     descriptor.exists = 0;
  30.     while (1) //Цикл меню
  31.     {
  32.         printf("Choose function.\n1 - create queue.\n2 - output queue.\n3 - add new element in queue.\n4 - delete element from queue.\n5 - delete queue.\n0 - exit.\nChosen function - "); //Выбор действия
  33.         scanf("%d*[^\n]", &key); //Ввод клавиши действия
  34.         switch (key)
  35.         {
  36.         case 1: //Создание очереди
  37.         {
  38.             create_queue(&descriptor);
  39.             break;
  40.         }
  41.         case 2: //Вывод очереди на экран или в файл
  42.         {
  43.             output_queue(&descriptor);
  44.             break;
  45.         }
  46.         case 3: //Добавление элемента очереди
  47.         {
  48.             add_element(&descriptor);
  49.             printf("Printing the queue:\n");
  50.             output_queue(&descriptor);
  51.             break;
  52.         }
  53.         case 4: //Удаление (выборка) элемента очереди
  54.         {
  55.             delete_element(&descriptor);
  56.             printf("Head element was successfully deleted.\n");
  57.             printf("Printing the queue:\n");
  58.             output_queue(&descriptor);
  59.             break;
  60.         }
  61.         case 5: //Очистка (удаление) очереди
  62.         {
  63.             clear_queue(&descriptor);
  64.             break;
  65.         }
  66.         case 0:
  67.         {
  68.             printf("Exiting program.\n"); //Выход из программы
  69.             break;
  70.         }
  71.         default: //Если выбранной команды не существует
  72.         {
  73.             printf("This feature doesn't exist. Please try again.\n");
  74.             break;
  75.         }
  76.         }
  77.         if (key == 0)
  78.             break;
  79.     }
  80. }
  81. void create_queue(struct descriptor *descriptor) //Подпрограмма создания очереди
  82. {
  83.     int i, len;
  84.     int N = 20; //Кол-во элементов жёстко задано в задании
  85.     FILE *in;
  86.     char str[256];
  87.     struct queue_element *ptr;
  88.  
  89.     if (descriptor->exists == 1)
  90.     {
  91.         printf("Queue already exists. Please, delete it before creating a new one.");
  92.         return;
  93.     }
  94.  
  95.     in = fopen("C:\\test\\SiAODlab3Input.txt", "rt");
  96.     if (in == NULL) //Если файл не удалось открыть
  97.     {
  98.         printf("Couldn't open file.\nFile full name: C:\\test\\SiAODlab3Input.txt\n");
  99.         return;
  100.     }
  101.  
  102.     if (fgets(str, 256, in) == NULL) //Если первая строка не считалась
  103.     {
  104.         printf("The file is empty or some error has occured while reading file.\nFile full name: C:\\test\\SiAODlab3Input.txt\n");
  105.         fclose(in);
  106.         return;
  107.     }
  108.  
  109.     ptr = malloc(sizeof(struct queue_element)); //Выделение памяти под первый элемент очереди
  110.     ptr->next = NULL; //Следующего элемента нет
  111.     descriptor->head = ptr; //Элемент единственный, это голова очереди
  112.     descriptor->tail = ptr; //Элемент единственный, это хвост очереди
  113.     descriptor->exists = 1;
  114.  
  115.     len = strlen(str);
  116.     if (str[len - 1] == '\n') //Удаление символа перехода на новую строку, если есть
  117.     {
  118.         str[len - 1] = '\0';
  119.         len = strlen(str);
  120.     }
  121.     ptr->data = calloc(len + 1, sizeof(char)); //Выделение памяти под строку
  122.     strcpy(ptr->data, str); //Запись данных в новый элемент
  123.  
  124.     for (i = 1; i < N; i++)
  125.     {
  126.         if (fgets(str, 256, in) == NULL) //Если очередная строка не считалась успешно
  127.         {
  128.             printf("Some error has occured while reading file.\nFile full name: C:\\test\\SiAODlab3Input.txt\n");
  129.             fclose(in);
  130.             clear_queue(descriptor);
  131.             return;
  132.         }
  133.         ptr = malloc(sizeof(struct queue_element));
  134.         ptr->next = NULL; //Это последний добавленный элемент
  135.         descriptor->tail->next = ptr; //Запись в прошлый последний элемент указателя на новый элемент
  136.         descriptor->tail = ptr; //Запись в дескриптор указателя на новый последний элемент
  137.  
  138.         len = strlen(str);
  139.         if (str[len - 1] == '\n') //Удаление символа перехода на новую строку, если есть
  140.         {
  141.             str[len - 1] = '\0';
  142.             len = strlen(str);
  143.         }
  144.         ptr->data = calloc(len + 1, sizeof(char)); //Выделение памяти под строку
  145.         strcpy(ptr->data, str); //Запись данных в новый элемент
  146.     }
  147.     fclose(in);
  148.     printf("Queue created succesfully.\n");
  149. }
  150.  
  151. void output_queue(struct descriptor *descriptor) //Подпрограмма вывода очереди на экран или в файл
  152. {
  153.     int action, i;
  154.     struct queue_element *ptr;
  155.     FILE *out;
  156.  
  157.     if (descriptor->exists == 0)
  158.     {
  159.         printf("The queue doesn't exist.\n");
  160.         return;
  161.     }
  162.  
  163.     printf("Choose the type of output:\n1 - on the screen.\n2 - in a file.\nEntered: ");
  164.     scanf("%d", &action);
  165.  
  166.     i = 0;
  167.     if (action == 1) //Вывод на экран
  168.     {
  169.         ptr = descriptor->head;
  170.         while (ptr != NULL)
  171.         {
  172.             i++;
  173.             printf("[%d]: %s\n", i,  ptr->data);
  174.             ptr = ptr->next;
  175.         }
  176.     }
  177.     else if (action == 2) //Вывод в файл
  178.     {
  179.         out = fopen("C:\\test\\SiAODlab3Output.txt", "wt");
  180.         if (out == NULL)
  181.         {
  182.             printf("Couldn't open file");
  183.             fclose(out);
  184.             return;
  185.         }
  186.         ptr = descriptor->head;
  187.         while (ptr != NULL)
  188.         {
  189.             i++;
  190.             if (fprintf(out, "[%d]: %s\n", i, ptr->data) < 0) //Если возникла ошибка
  191.             {
  192.                 remove("C:\\test\\SiAODlab3Output.txt");
  193.                 printf("An error has occured while writing into a file.\n");
  194.                 fclose(out);
  195.                 return;
  196.             }
  197.             ptr = ptr->next;
  198.         }
  199.         fclose(out);
  200.         printf("Output file was successfully created and filled.\nFile full name: C:\\test\\SiAODlab3Output.txt\n");
  201.     }
  202.     else //Некорректоный ввод
  203.     {
  204.         printf("Incorrect input.\n");
  205.         return;
  206.     }
  207. }
  208. void add_element(struct descriptor *descriptor) //Подпрограмма добавления элемента в очередь
  209. {
  210.     struct queue_element *ptr;
  211.     char str[256];
  212.     int len;
  213.  
  214.     if (descriptor->exists == 0)
  215.     {
  216.         printf("The queue doesn't exist.\n");
  217.         return;
  218.     }
  219.  
  220.     printf("Enter data for the new queue element.\n");
  221.     scanf("%*c");
  222.     fgets(str, 256, stdin);
  223.  
  224.     len = strlen(str);
  225.     if (str[len - 1] == '\n') //Удаление символа перехода на новую строку, если есть
  226.     {
  227.         str[len - 1] = '\0';
  228.         len = strlen(str);
  229.     }
  230.  
  231.     ptr = malloc(sizeof(struct queue_element)); //Выделение памяти под новый элемент очереди
  232.     ptr->data = calloc(len + 1, sizeof(char)); //Выделение памяти под строку
  233.     strcpy(ptr->data, str);
  234.     descriptor->tail->next = ptr;
  235.     ptr->next = NULL;
  236.     descriptor->tail = ptr;
  237.     printf("New queue element was successfully added.\n");
  238. }
  239.  
  240. void delete_element(struct descriptor *descriptor) //Подпрограмма выборки элемента из очереди
  241. {
  242.     struct queue_element *ptr;
  243.  
  244.     if (descriptor->exists == 0)
  245.     {
  246.         printf("The queue doesn't exist.\n");
  247.         return;
  248.     }
  249.  
  250.     if (descriptor->head == descriptor->tail) //Если в очереди только один элемент
  251.     {
  252.         free(descriptor->head->data);
  253.         free(descriptor->head);
  254.         descriptor->head = NULL;
  255.         descriptor->tail = NULL;
  256.         descriptor->exists = 0;
  257.         printf("Queue was deleted.\n");
  258.     }
  259.     else
  260.     {
  261.         ptr = descriptor->head->next;
  262.         free(descriptor->head->data);
  263.         free(descriptor->head);
  264.         descriptor->head = ptr;
  265.     }
  266. }
  267. void clear_queue(struct descriptor *descriptor) //Подпрограмма очистки очереди
  268. {
  269.     if (descriptor->exists == 0)
  270.     {
  271.         printf("The queue doesn't exist.\n");
  272.         return;
  273.     }
  274.  
  275.     while (descriptor->exists == 1)
  276.     {
  277.         delete_element(descriptor);
  278.     }
  279. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement