#include <stdio.h>
#include <ctype.h>
void readFile(FILE *file);
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces);
void printMessage(int *alpha, int *digit, int *punct, int *spaces);
int main( void ) {
FILE *file = NULL;
readFile(file);
return 0;
}
void readFile(FILE *file) {
file = fopen("/Users/AdmiralDanny/Desktop/testFile.txt", "r");
int *alpha = NULL, *digit = NULL, *punct = NULL, *space = NULL;
if (file) {
count(file, alpha, digit, punct, space);
fclose(file);
} else {
perror( "error opening the file" );
}
}
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces) {
int ch;
while ((ch = fgetc(file)) != EOF ) {
if (isalpha(ch) != 0) {
++alpha;
} else if (isdigit(ch)) {
++digit;
} else if (ispunct(ch)) {
++punct;
} else if (isspace(ch)) {
++spaces;
}
}
printMessage(alpha, digit, punct, spaces);
}
void printMessage(int *alpha, int *digit, int *punct, int *spaces) {
printf( "alphabetic characters: %d\n", alpha );
printf( "digit characters: %d\n", digit);
printf( "punctuation characters: %d\n", punct );
printf( "whitespace characters: %d\n", spaces );
}
my .txt file only has 4 spaces and 12 alphabet character, but it gives me 48 alphabetic characters and 8 white space characters? why is this happening?
also, i get a warning when i tried to print out the int pointeres in printMessage method
No memory has been allocated for any of the
ints and thecount()function is just incrementing theintpointers not anintvalue:You could use
malloc(), but it would simpler to stack allocate and pass the addresses in.and in
count():dereference the
ints for incrementing and dereference for printing:As the caller of
count()does not require the updated values of theints, just pass by value and forget about pointers altogether (same forprintMessage()).