Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.84 KB | None | 0 0
  1. ///
  2. /// @file    wc.cpp
  3. ///
  4. /// @author  David Liang
  5. /// @brief   Lab 01 - wc - EE 491F - Spr 2020
  6. ///
  7.  
  8. #define _CRT_SECURE_NO_DEPRECATE /* allow fopen to be used w/o error */
  9. #define WHITESPACE(n) (n == ' ' || n == '\t' || n == '\n' || n == '\0')
  10. #define FILESIZE 100
  11.  
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <errno.h>
  15.  
  16.  
  17.  
  18. int main(int argc, char** argv) {
  19.  
  20.     /* output header */
  21.     printf("char\tword\tline\tfile\n");
  22.  
  23.     for (int i = 1; i < argc; i++) {
  24.  
  25.         /* 1. Get the FILE from the command line. If there is no filename, post an error message: Usage:  wc FILE */
  26.  
  27.         /* no file is passed */
  28.         if (argc == 0) {
  29.             printf("ERROR: no file is passed");
  30.             return 0;
  31.         }
  32.  
  33.         /* Variable Declaration */
  34.         FILE* fp;
  35.         char filename[FILESIZE] = "",
  36.              charinc = 0;
  37.         int lines = 0,
  38.             words = 0,
  39.             characters = 0;
  40.  
  41.        
  42.  
  43.         /* 2. Try to open FILE.  If the file can’t be opened, post an error message: program: Can’t open [FILE], substituting in the filename. */
  44.         fp = fopen(argv[i], "r");
  45.         if (fp == NULL) {
  46.             fprintf(stderr, "Can't open %s: %s\n", argv[i], strerror(errno));
  47.         }
  48.         else {
  49.             //printf("DEBUG: it worked!\n");
  50.             while ((charinc = fgetc(fp)) != EOF)
  51.             {
  52.                 /* increment character count */
  53.                 if (!WHITESPACE(charinc)) {
  54.                     characters++;
  55.                 }
  56.  
  57.                 /* increment line count */
  58.                 if (charinc == '\n' || charinc == '\0') {
  59.                     lines++;
  60.                 }
  61.  
  62.                 /* increment word count */
  63.                 if (WHITESPACE(charinc)) {
  64.                     words++;
  65.                 }
  66.             }
  67.  
  68.             /* increment word count and line count for last word */
  69.             if (characters > 0) {
  70.                 words++;
  71.                 lines++;
  72.             }
  73.  
  74.             /* 3. If FILE can be processed, then count the number of chars, words and lines and output: nn <tab> ww <tab> cc <tab> FILE */
  75.             printf("%d\t%d\t%d\t%s\n", characters, words, lines, argv[i]);
  76.         }
  77.  
  78.         fclose(fp);
  79.     }
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement