Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
3.3 KiB

  1. /*
  2. * wc.c - counts lines, words and chars. A word is defined as a
  3. * maximal string of non-blank characters separated by blanks.
  4. */
  5. #include <ctype.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <process.h>
  9. #include <windows.h>
  10. #include <tools.h>
  11. /*
  12. * options flags
  13. */
  14. int lflg, wflg, cflg, tflg;
  15. unsigned long sumlines, sumwords, sumchars;
  16. void
  17. usage()
  18. {
  19. fprintf(stderr, "usage: wc [-lwc] [files]\n" );
  20. exit(EXIT_FAILURE);
  21. }
  22. void
  23. wc( fh )
  24. FILE *fh;
  25. {
  26. unsigned long lines, words, chars;
  27. int ch, inword = 0;
  28. lines = words = chars = 0L;
  29. while (1)
  30. {
  31. if ((ch = getc(fh)) == EOF ) break;
  32. ++chars;
  33. if ( isspace(ch) )
  34. {
  35. if ( inword )
  36. inword = 0;
  37. if ( ch == '\n' )
  38. ++lines;
  39. continue;
  40. }
  41. if ( isalnum(ch) && !inword )
  42. {
  43. inword = 1;
  44. ++words;
  45. }
  46. }
  47. if ( lflg ) printf(" %10lu", lines );
  48. if ( wflg ) printf(" %10lu", words );
  49. if ( cflg ) printf(" %10lu", chars );
  50. sumlines += lines;
  51. sumwords += words;
  52. sumchars += chars;
  53. return;
  54. }
  55. __cdecl
  56. main(
  57. int argc,
  58. char **argv
  59. )
  60. {
  61. FILE *fh;
  62. char *p;
  63. SHIFT( argc, argv );
  64. while ( argc > 0 && ( **argv == '-' || **argv == '/' ) )
  65. {
  66. p = *argv;
  67. while (*++p)
  68. {
  69. switch(*p)
  70. {
  71. case 'l':
  72. lflg++;
  73. break;
  74. case 'w':
  75. wflg++;
  76. break;
  77. case 'c':
  78. cflg++;
  79. break;
  80. case '?':
  81. default:
  82. usage();
  83. }
  84. }
  85. SHIFT( argc, argv );
  86. }
  87. if (!(lflg||wflg||cflg)) lflg = wflg = cflg = 1;
  88. if ( argc > 1 ) tflg++; /* print totals */
  89. if ( argc == 0 )
  90. {
  91. wc( stdin );
  92. printf("\n");
  93. }
  94. else
  95. {
  96. while ( argc )
  97. {
  98. if (( fh = fopen( *argv, "rb" )) == NULL )
  99. {
  100. perror( *argv );
  101. SHIFT( argc, argv );
  102. continue;
  103. }
  104. wc( fh );
  105. fclose( fh );
  106. printf ("\t%s\n", *argv );
  107. SHIFT( argc, argv );
  108. }
  109. if ( tflg )
  110. {
  111. if ( lflg ) printf(" %10lu", sumlines );
  112. if ( wflg ) printf(" %10lu", sumwords );
  113. if ( cflg ) printf(" %10lu", sumchars );
  114. printf("\tTotals\n");
  115. }
  116. }
  117. return (EXIT_SUCCESS);
  118. }