В файле оставить только по одному экземпляру каждого слова - C (СИ)
Формулировка задачи:
ОБРАБОТКА ДИНАМИЧЕСКИХ МАССИВОВ И СВЯЗНЫХ СПИСКОВ ДАННЫХ
задача на си. предполагается для размещения в памяти содержимого файлов использовать односвязные линейные списки.
Дан текстовый файл. Группы символов, разделенные пробелами, будем называть словами. В файле оставить только по одному экземпляру каждого слова и добавить перед ними количество их вхождений в первоначальный текст.
Помогите,пожалуйста!
Решение задачи: «В файле оставить только по одному экземпляру каждого слова»
textual
Листинг программы
// Test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #include <ctype.h> typedef struct WD { char word[256]; int pos; int len; int count; WD* prev; WD* next; } WD; WD *list = NULL, *tail = NULL; WD* getword(int n) { WD* node_wd = list; for (int i = 0; node_wd != NULL; node_wd = node_wd->next, i++) if (i == n) return node_wd; return node_wd; } int getcount() { WD* node_wd = list; int count = 0; for (count = 0; node_wd != NULL; count++) node_wd = node_wd->next; return count; } int main() { FILE* fp = NULL; const char* filename = "d:\\input.txt"; if ((fp = fopen(filename,"r")) == NULL) printf("Unable to open file %s for reading\n",filename); bool endoffile = false; char ch = '\0'; char temp[256] = "\0"; for (int i = 0, q = 0; (ch = fgetc(fp)) != EOF || !endoffile; i++) if (!isspace(ch) && ch > 0) temp[q++] = ch; else { temp[q] = '\0'; q = 0; WD* node_wd = (WD*)malloc(sizeof(WD)); if (node_wd != NULL) { strcpy(node_wd->word,temp); node_wd->count = 0; node_wd->len = strlen(temp); node_wd->pos = i - node_wd->len; node_wd->prev = tail; node_wd->next = NULL; if (list == NULL) { list = node_wd; tail = list; } else { tail->next = node_wd; tail = node_wd; } endoffile = (ch < 0) ? 1 : 0; } } for (int t = 0; t < getcount(); t++) { WD* node_wd = getword(t); int cnt = 0; for ( ;node_wd != NULL; node_wd = node_wd->next) if (!strcmp(node_wd->word, getword(t)->word)) cnt++; bool found = false; WD* node_wd_r = getword(t)->prev; char* word = getword(t)->word; while (node_wd_r != NULL && !found) { found = (!strcmp(node_wd_r->word, word)) ? 1 : 0; node_wd_r = node_wd_r->prev; } if (found == false) getword(t)->count = cnt; } fclose(fp); FILE* fp_out = NULL; if ((fp_out = fopen(filename,"w")) == NULL) printf("Unable to open file %s for writing\n",filename); for ( ; list != NULL; list = list->next) if (list->count > 0) fprintf(fp,"%d %s ",list->count, list->word); fprintf(fp,"\n"); fclose(fp_out); _getch(); return 0; }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д