Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///
- /// @file wc.cpp
- ///
- /// @author David Liang
- /// @brief Lab 01 - wc - EE 491F - Spr 2020
- ///
- #define _CRT_SECURE_NO_DEPRECATE /* allow fopen to be used w/o error */
- #define WHITESPACE(n) (n == ' ' || n == '\t' || n == '\n' || n == '\0')
- #define FILESIZE 100
- #include <stdio.h>
- #include <string.h>
- #include <errno.h>
- int main(int argc, char** argv) {
- /* output header */
- printf("char\tword\tline\tfile\n");
- for (int i = 1; i < argc; i++) {
- /* 1. Get the FILE from the command line. If there is no filename, post an error message: Usage: wc FILE */
- /* no file is passed */
- if (argc == 0) {
- printf("ERROR: no file is passed");
- return 0;
- }
- /* Variable Declaration */
- FILE* fp;
- char filename[FILESIZE] = "",
- charinc = 0;
- int lines = 0,
- words = 0,
- characters = 0;
- /* 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. */
- fp = fopen(argv[i], "r");
- if (fp == NULL) {
- fprintf(stderr, "Can't open %s: %s\n", argv[i], strerror(errno));
- }
- else {
- //printf("DEBUG: it worked!\n");
- while ((charinc = fgetc(fp)) != EOF)
- {
- /* increment character count */
- if (!WHITESPACE(charinc)) {
- characters++;
- }
- /* increment line count */
- if (charinc == '\n' || charinc == '\0') {
- lines++;
- }
- /* increment word count */
- if (WHITESPACE(charinc)) {
- words++;
- }
- }
- /* increment word count and line count for last word */
- if (characters > 0) {
- words++;
- lines++;
- }
- /* 3. If FILE can be processed, then count the number of chars, words and lines and output: nn <tab> ww <tab> cc <tab> FILE */
- printf("%d\t%d\t%d\t%s\n", characters, words, lines, argv[i]);
- }
- fclose(fp);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement