Expand|Select|Wrap|Line Numbers
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdlib.h>
- struct word {
- struct word *left; /* tree to the left */
- struct word *right; /* tree to the right */
- char *WORD;
- int count;
- }word;
- static struct word *root = NULL;
- void memory_error(void)
- {
- fprintf(stderr, "not enough memory\n");
- exit(8);
- }
- char *fp(char *fp)
- {
- char *p;
- p = (char*)malloc((unsigned) (strlen(fp) + 1));
- if (p == NULL)
- memory_error();
- strcpy(p, fp);
- int compword(const void *WORD1, const void *WORD2);
- return (p);
- }
- void enter(struct word **word, char *WORD)
- {
- int result;
- char *fp(char *);
- if ((*word) == NULL) {
- (*word) = ((word*)malloc(sizeof(struct word)));
- if ((*word) == NULL)
- {printf("not enough mem");
- exit(1);
- }
- }
- (*word)->left = NULL;
- (*word)->right = NULL;
- (*word)->WORD = fp(WORD);
- (*word)->count=1;
- return;
- }
- result = strcmp((*WORD)->word,WORD);
- if (result == 0);
- {
- (*word)->count+=1;
- return;
- }
- if (result < 0);
- {{
- enter(&((*word)->right),WORD) ;
- else
- enter(&((*word)->left),WORD);
- }
- void scan(char *name)
- {
- char WORD[100];
- int index;
- int ch;
- FILE *f;
- f = fopen(name, "r");
- if (f == NULL) {
- fprintf(stderr, "Unable to open %s\n", name);
- exit(8);
- }
- while (1) {
- ch = fgetc(f);
- if (isalpha(ch) || (ch == EOF))
- break;
- }
- if (ch == EOF)
- break;
- WORD[0] = ch;
- for (index = 1; index < sizeof(WORD); ++index) {
- ch = fgetc(f);
- if (!isalpha(ch))
- break;
- WORD[index] = ch;
- }
- WORD[index] = '\0';
- enter(&root, WORD);
- }
- fclose(f);
- }
- void print_tree(struct word *top)
- {
- if (top == NULL)
- return;
- print_tree(top->left);
- printf("%s\n", top->WORD);
- print_tree(top->right);
- }
- int main(int argc, char *argv[])
- {
- if (argc != 2) {
- fprintf(stderr, "Wrong number of parameters\n");
- fprintf(stderr, " on the command line\n");
- fprintf(stderr, "Usage is:\n");
- fprintf(stderr, " words 'file'\n");
- exit(8);
- }
- scanf(argv[1]);
- print_tree(root);
- return (0);
- }