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. void dump(struct word *p) {
  86. if (p == 0)
  87. return;
  88. printf("%s(%d)\n", p->name, p->count);
  89. dump(p->next);
  90. }
  91.  
  92. int main() {
  93. char buf[N];
  94. FILE *fp;
  95.  
  96. fp = fopen("anne_short.txt","r");
  97. if(fp == NULL){
  98. printf("File read error!\n");
  99. exit(1);
  100. }
  101.  
  102. int n;
  103. struct word *root;
  104. root = 0;
  105.  
  106. for (;;) {
  107. n = read_word(fp, buf);
  108. if (n == 0)
  109. break;
  110. addword(&root, buf);
  111. }
  112. dump(root);
  113. fclose(fp);
  114. return 0;
  115. }
  116. /* end */
  117.  
Runtime error #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
File read error!