Guest User

Untitled

a guest
Nov 21st, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define STATE_START 0
  6. #define STATE_INWORD 1
  7. #define STATE_INSPACE 2
  8. #define STATE_DISPLAY 3
  9. #define STATE_END 4
  10.  
  11. typedef int State;
  12.  
  13. int main(int argc, const char *argv[])
  14. {
  15. FILE *f;
  16. int cc = 0, wc = 0, lc = 0;
  17. char ch = 0;
  18. State state = STATE_START;
  19.  
  20. if(argc > 2) {
  21. fprintf(stderr, "Usage:wc [filename]\n");
  22. fprintf(stderr, " :wc < filename\n");
  23. exit(1);
  24. }
  25.  
  26. if(argc == 2) {
  27. f = fopen(argv[1], "r");
  28. if(f == NULL){
  29. fprintf(stderr, "Can't read %s\n", argv[1]);
  30. exit(1);
  31. }
  32. }else if(argc == 1) {
  33. f = stdin;
  34. }
  35.  
  36. while(1){
  37. if(state == STATE_START){
  38. ch = getc(f);
  39. state = STATE_INSPACE;
  40. }
  41. if(state == STATE_INWORD){
  42. if(ch == EOF){
  43. state = STATE_DISPLAY;
  44. }else if(ch == '\n'){
  45. ch = getc(f);
  46. cc++;
  47. wc++;
  48. lc++;
  49. state = STATE_INSPACE;
  50. }else if(ch == '\t' || ch == ' '){
  51. ch = getc(f);
  52. cc++;
  53. wc++;
  54. state = STATE_INSPACE;
  55. }else{
  56. ch = getc(f);
  57. cc++;
  58. state = STATE_INWORD;
  59. }
  60. }else if(state == STATE_INSPACE){
  61. if(ch == EOF){
  62. state = STATE_DISPLAY;
  63. }else if(ch == '\n'){
  64. ch = getc(f);
  65. cc++;
  66. lc++;
  67. state = STATE_INSPACE;
  68. }else if(ch == '\t' || ch == ' '){
  69. ch = getc(f);
  70. cc++;
  71. state = STATE_INSPACE;
  72. }else{
  73. ch = getc(f);
  74. cc++;
  75. state = STATE_INWORD;
  76. }
  77. }else if(state == STATE_DISPLAY){
  78. printf("%d %d %d\n", lc, wc, cc);
  79. state = STATE_END;
  80. }else if(state == STATE_END){
  81. break;
  82. }else{
  83. fprintf(stderr, "error\n");
  84. exit(1);
  85. }
  86. }
  87.  
  88. return 0;
  89. }
Add Comment
Please, Sign In to add comment