Dziś jako ćwiczenie napisałem prosty program zliczający wystąpienia słów w pliku tekstowym i chciałbym się nim podzielić w celu uzyskania komentarzy (a może nawet ktoś użyje tego programu).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORDLEN 16
struct wordent
{ char word[WORDLEN];
int count;
struct wordent *next;
};
struct wordent *wordlist = NULL;
void regword (char *word)
{ struct wordent *ent;
for (ent = wordlist; ent; ent = ent->next)
if (!strcmp (word, ent->word))
{ ++(ent->count);
return;
}
ent = malloc (sizeof (struct wordent));
strcpy (ent->word, word);
ent->count = 1;
ent->next = wordlist;
wordlist = ent;
}
void freelist (struct wordent *top)
{ if (top)
{ freelist (top->next);
free (top);
}
}
int main (int argc, char **argv)
{ FILE *fp = stdin;
char c, wordbuf[WORDLEN], wlen = 0;
int maxcount, n = 0;
struct wordent *ent, *maxent;
if (argc > 1)
fp = fopen (argv[1], "r");
if (!fp)
{ puts ("Can't read the input file.");
return 1;
}
do
{ c = fgetc (fp);
if (c >= 'A' && c <= 'Z')
c |= 32;
if (c >= 'a' && c <= 'z')
{ if (wlen < (WORDLEN - 1))
wordbuf[wlen++] = c;
} else if (wlen)
{ wordbuf[wlen] = 0;
regword (wordbuf);
wlen = 0;
}
} while (c != EOF);
list:
maxent = NULL; maxcount = 0;
for (ent = wordlist; ent; ent = ent->next)
if (ent->count > maxcount)
{ maxent = ent;
maxcount = maxent->count;
}
if (maxent)
{ printf ("Word \"%s\" %d times.\n", maxent->word, maxcount);
maxent->count = 0;
++n;
goto list;
}
printf ("Total %d unique words.\n", n);
freelist (wordlist);
return 0;
}