fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5.  
  6. #define N 20
  7.  
  8. int my_isspace(char c) {
  9. return (c == ' ' || c == ',' || c == '.' || c == '\n');
  10. }
  11.  
  12. int read_word(FILE *fp,char buf[N]){
  13. int i=0;
  14. for(i=0;i<N;i++){
  15. buf[i] = '\0';
  16. }
  17.  
  18. char c;
  19. while (c = fgetc(fp), c != EOF && my_isspace(c))
  20. ;
  21. if (c == EOF)
  22. return 0;
  23. buf[0] = c;
  24. i = 1;
  25. while(((c = fgetc(fp)) != EOF) && i < N - 1) {
  26. buf[i] = c;
  27. if(my_isspace(c)){
  28. buf[i] = '\0';
  29. break;
  30. }
  31. i++;
  32. }
  33. if (c == EOF) {
  34. buf[i] = '\0';
  35. }
  36. if (i == N - 1) {
  37. ungetc(c, fp);
  38. buf[N - 1] = '\0';
  39. }
  40. return i;
  41. }
  42.  
  43. struct word {
  44. char name[N];
  45. int count;
  46. struct word *next;
  47. };
  48.  
  49. struct word *create_word(char buf[N]) {
  50. struct word *p;
  51. if ((p = malloc(sizeof(struct word))) == 0) {
  52. printf("memory full, aborted.\n");
  53. exit(1);
  54. }
  55. strcpy(p->name, buf);
  56. p->count = 1;
  57. return p;
  58. }
  59.  
  60. void insertword(struct word **root, char buf[N]) {
  61. struct word *p;
  62. p = create_word(buf);
  63. p->next = *root;
  64. *root = p;
  65. }
  66.  
  67.  
  68. void addword(struct word **root, char buf[N]) {
  69. int c;
  70. if (*root == 0) {
  71. insertword(root, buf);
  72. } else {
  73. c = strcmp((*root)->name, buf);
  74. if (c == 0) {
  75. (*root)->count++;
  76. return;
  77. } else if (c > 0) {
  78. insertword(root, buf);
  79. } else {
  80. addword(&((*root)->next), buf);
  81. }
  82. }
  83. }
  84.  
  85. struct Output {
  86. char *word;
  87. };
  88. struct Output Message[400];
  89. int idx = 0;
  90.  
  91. void dump(struct word *p) {
  92. if (p == 0)
  93. return;
  94. printf("%s(%d)\n", p->name, p->count);
  95. Message[idx++].word = p->name;
  96. dump(p->next);
  97. }
  98.  
  99. int main() {
  100. char buf[N];
  101. FILE *fp;
  102.  
  103. fp = fopen("anne_short.txt","r");
  104. if(fp == NULL){
  105. printf("File read error!\n");
  106. exit(1);
  107. }
  108.  
  109. int n;
  110. struct word *root;
  111. root = 0;
  112.  
  113. for (;;) {
  114. n = read_word(fp, buf);
  115. if (n == 0)
  116. break;
  117. addword(&root, buf);
  118. }
  119. dump(root);
  120.  
  121. for (int i = 0; i < idx; i++) {
  122. printf("%s: ", Message[i].word);
  123. if (i > 0) printf("%s", (strcmp(Message[i - 1].word, Message[i].word) < 0) ? "OK" : "NoGOOD");
  124. putchar('\n');
  125. }
  126. fclose(fp);
  127. return 0;
  128. }
  129. /* end */
  130.  
  131.  
Runtime error #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
File read error!