Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // file_and_tree.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
- // Из текстового файла добавлять и упорядочивать слова в дерево
- #include "pch.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <string.h>
- struct tree
- {
- char* str;
- struct tree* parent;
- struct tree* right;
- struct tree* left;
- int repeats;
- };
- FILE* file_create(const char* filename, const char* mode)
- {
- FILE* file = fopen(filename, mode);
- if (!file)
- {
- fprintf(stderr, "Can't open file\n");
- return NULL;
- }
- return file;
- }
- void file_fill(FILE* file)
- {
- char c;
- for (;;)
- {
- c = _getch();
- fputc(c, stdout);
- if (c == 'x')
- {
- break;
- }
- fprintf(file, "%c", c);
- }
- }
- void file_output(FILE* file)
- {
- rewind(file);
- printf("\n");
- char c;
- while (!feof(file))
- {
- c = fgetc(file);
- if (feof(file)) break;
- fputc(c, stdout);
- }
- printf("\n");
- }
- struct tree* add_element_recursive(struct tree* node, char* str)
- {
- if (!node)
- {
- node = (struct tree*)malloc(sizeof(struct tree));
- node->left = node->right = NULL;
- node->repeats = 1;
- node->str = (char*)malloc(sizeof(char) * (strlen(str) + 1));
- strcpy(node->str, str);
- }
- else
- {
- if (strcmp(str, node->str) == 0)
- {
- node->repeats++;
- }
- else
- {
- if (strcmp(str, node->str) < 0)
- {
- node->left = add_element_recursive(node->left, str);
- }
- else
- {
- node->right = add_element_recursive(node->right, str);
- }
- }
- }
- return node;
- }
- void find_words(FILE* file, struct tree** node)
- {
- char* str = NULL;
- char c;
- int lenght = 0;
- rewind(file);
- while (!feof(file))
- {
- c = fgetc(file);
- if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || feof(file))
- {
- if (lenght > 0)
- {
- str = (char*)realloc(str, sizeof(char) * (++lenght));
- str[lenght - 1] = '\0';
- *node = add_element_recursive(*node, str);
- }
- free(str);
- if (feof(file))
- {
- return;
- }
- else
- {
- lenght = 0;
- str = NULL;
- }
- }
- else
- {
- str = (char*)realloc(str, sizeof(char) * (++lenght));
- str[lenght - 1] = c;
- }
- }
- }
- void tree_output(struct tree* node)
- {
- if (node)
- {
- if (node->left)
- {
- tree_output(node->left);
- }
- puts(node->str);
- if (node->right)
- {
- tree_output(node->right);
- }
- }
- }
- int main()
- {
- FILE* file = file_create("text.txt", "w+");
- file_fill(file);
- file_output(file);
- struct tree* node = NULL;
- find_words(file, &node);
- tree_output(node);
- fclose(file);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment