logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul01/readCharFile2.c

/*

here, we're using functions from the ctype library to get information about
each character in the file

more info:
- https://www.tutorialspoint.com/c_standard_library/ctype_h.htm

- https://en.wikibooks.org/wiki/C_Programming/ctype.h

each of these functions returns a nonzero for true, or zero if false
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[]){

	if(argc < 2){
		fprintf(stderr, "%s filename\n", argv[0]);
		exit(1);
	}

	FILE *fp;

	fp = fopen(argv[1], "r");

	if(fp == NULL){
		fprintf(stderr, "Cannot open file\n");
		exit(-1);
	}

	char ch;
	int alphaCount = 0;
	int spaceCount = 0;
	int totalCount = 0;

	while((ch = fgetc(fp)) != EOF){
		if(isalpha(ch) > 0) //is this an alphabet character?
		   alphaCount++;

		if(isspace(ch) > 0)//is this a space character?
			spaceCount++;

		totalCount++; //counting total characters

	}

	printf("Number of alphabet characters entered: %d\n", alphaCount);
	printf("Number of space characters entered: %d\n", spaceCount);
	printf("Total characters: %d\n", totalCount);

	return 0;

}