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. void addword(struct word **root, char buf[N]) {
  50.  
  51. if (*root == 0) {
  52. struct word *p;
  53. if ((p = malloc(sizeof(struct word))) == 0) {
  54. printf("memory full, aborted.\n");
  55. exit(1);
  56. }
  57. strcpy(p->name, buf);
  58. p->count = 1;
  59. p->next = *root;
  60. *root = p;
  61. return;
  62. } else {
  63. if (strcmp((*root)->name, buf) == 0) {
  64. (*root)->count++;
  65. return;
  66. } else {
  67. addword(&((*root)->next), buf);
  68. }
  69. }
  70. }
  71.  
  72. void dump(struct word *p) {
  73. if (p == 0)
  74. return;
  75. printf("%s(%d)\n", p->name, p->count);
  76. dump(p->next);
  77. }
  78.  
  79. int main() {
  80. char buf[N];
  81. FILE *fp;
  82.  
  83. fp = fopen("anne_short.txt","r");
  84. if(fp == NULL){
  85. printf("File read error!\n");
  86. exit(1);
  87. }
  88.  
  89. int n;
  90. struct word *root;
  91. root = 0;
  92.  
  93. for (;;) {
  94. n = read_word(fp, buf);
  95. if (n == 0)
  96. break;
  97. addword(&root, buf);
  98. }
  99. dump(root);
  100. fclose(fp);
  101. return 0;
  102. }
  103. /* end */
  104.  
Runtime error #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
File read error!