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