옵션 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> #include <fcntl.h> #include <ctype.h> typedef struct Word { char word[BUFSIZ]; int count; struct Word *pre; struct Word *next; } Word; Word *create_word(char *s) { Word *new_word; new_word = (Word *)malloc(sizeof(Word)); if(new_word==NULL) printf("error malloc\n"); strcpy(new_word->word, s); new_word->count = 0; new_word->pre = NULL; new_word->next = NULL; return new_word; } void insert_word(Word **head, char *w) { Word *new_word = create_word(w); Word *s = *head; if(*head == NULL) { new_word->count++; new_word->pre = *head; *head = new_word; } else if(strcmp(s->word, new_word->word)==1) { new_word->count++; new_word->pre = *head; new_word->next = s; s->pre = new_word; *head = new_word; } else { while(s->next != NULL) { if(strcmp(s->word, new_word->word)==-1) { s = s->next; } else break; } if(strcmp(s->word, new_word->word)==-1) { new_word->count++; new_word->pre = s; s->next = new_word; } else if(strcmp(s->word, new_word->word)==1) { s->pre->next = new_word; new_word->pre = s->pre; new_word->count++; new_word->next = s; s->pre = new_word; } else if(strcmp(s->word, new_word->word)==0) { s->count++; free(new_word); } } } main() { int fdr, fdw; Word *word; int c; char ch, buf, *buf_out, buffer[BUFSIZ]; off_t cur, end; if((fdr=open("the_gold_bug.txt", O_RDONLY))==-1) { perror("open : the_gold_bug.txt"); exit(1); } if((fdw=open("text.res2", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))==-1) { perror("open : text.res2"); exit(1); } while(read(fdr, &buf, 1)>0) { c = toascii(buf); if((c>='a' && c<='z') || (c>='A' && c<='Z')) { if(c>='A' && c<='Z') c+=32; sprintf(&ch, "%c", c); if(*buffer==0) strcpy(buffer, &ch); else strcat(buffer, &ch); } else { if(*buffer != 0) { insert_word(&word, buffer); } memset(buffer, '\0', sizeof(buffer)); } } while(word) { sprintf(buf_out, "%s\t%d\n", word->word, word->count); write(fdw, buf_out, strlen(buf_out)*sizeof(char)); word = word->next; } close(fdr); close(fdw); } | cs |