fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define N 20
  6.  
  7. int my_isspace(char c) {
  8. return (c == ' ' || c == ',' || c == '.' || c == '\n');
  9. }
  10.  
  11. int read_word(FILE *fp,char buf[N]){
  12. int i=0;
  13. for(i=0;i<N;i++){
  14. buf[i] = '\0';
  15. }
  16.  
  17. char c;
  18. while (c = fgetc(fp), c != EOF && my_isspace(c))
  19. ;
  20. if (c == EOF)
  21. return 0;
  22. buf[0] = c;
  23. i = 1;
  24. while(((c = fgetc(fp)) != EOF) && i < N - 1) {
  25. buf[i] = c;
  26. if(my_isspace(c)){
  27. buf[i] = '\0';
  28. break;
  29. }
  30. i++;
  31. }
  32. if (c == EOF) {
  33. buf[i] = '\0';
  34. }
  35. if (i == N - 1) {
  36. ungetc(c, fp);
  37. buf[N - 1] = '\0';
  38. }
  39. return i;
  40. }
  41.  
  42. struct word {
  43. char name[N];
  44. struct word *next;
  45. };
  46.  
  47. void addword(struct word **root, char buf[N]) {
  48. struct word *p;
  49. if ((p = malloc(sizeof(struct word))) == 0) {
  50. printf("memory full, aborted.\n");
  51. exit(1);
  52. }
  53. strcpy(p->name, buf);
  54. p->next = *root;
  55. *root = p;
  56. }
  57.  
  58. void dump(struct word *p) {
  59. if (p == 0)
  60. return;
  61. printf("%s\n", p->name);
  62. dump(p->next);
  63. }
  64.  
  65. int main() {
  66. char buf[N];
  67. FILE *fp;
  68.  
  69. fp = fopen("anne_short.txt","r");
  70. if(fp == NULL){
  71. printf("File read error!\n");
  72. exit(1);
  73. }
  74.  
  75. int n;
  76. struct word *root;
  77. root = 0;
  78.  
  79. for (;;) {
  80. n = read_word(fp, buf);
  81. if (n == 0)
  82. break;
  83. addword(&root, buf);
  84. }
  85. dump(root);
  86. fclose(fp);
  87. return 0;
  88. }
  89. /* end */
  90.  
Runtime error #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
File read error!