|
CS456 - Systems Programming
Spring 2026
|
Displaying ./code/jan28/wc_simple.c
/*
a simple implentation of the wc command
this takes a file and prints the count of lines, words and characters in a file
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> //needed for perror
int main(int argc, char **argv){
//check if file was provided , otherwise print usage statement and exit
if(argc < 2){
fprintf(stderr, "Usage: %s file\n", argv[0]);
exit(1);
}
//read in a file from the command line using fopen
FILE *fp = fopen(argv[1], "r");
// checking return value of fopen
// if fopen returns NULL, then it failed, so print error message and exit
if (fp == NULL){
perror("fopen");
exit(-1);
}
int c; //fgetc returns an int, hence declaring c as an int
//variable declarations for things we're keeping a count of
int lines = 0;
int words = 0;
int chars = 0;
//loop through entire file
while((c =fgetc(fp))!= EOF){
if(c == '\n'){ //see a new line. so increment the count of lines and words
lines++;
words++;
}
if(c == ' ') words++; //see a space character, so we probably have a word, so increment the count
chars++; //increment the count of characters
}
fclose(fp); //closing the file as we're done with it
//printing the results
printf("%s has %d lines, %d words, and %d characters\n", argv[1], lines, words, chars);
return 0;
}
|