// This illustrates how to read a file, stopping when an input failure occurs. // It also illustrates how to do a few character-related tricks that are // standard practice in C. #include #include #define NUMLWRCASE 26 int main() { FILE* fp; // Try to open file named "RoughingIt.txt"; if this fails, fopen() will // return NULL, so we can check for a failure easily: if ( ( fp = fopen("RoughingIt.txt", "r") ) == NULL ) { printf("Error, could not open file data.txt\n"); return 1; } char C; // holds current character read from file int cCount[NUMLWRCASE] = {0}; // holds counter for each lower-case letter // fscanf() returns the number of values read; we can use that to detect // an input failure, whether it is at the end of the file or elsewhere: while ( fscanf(fp, "%c", &C) == 1 ) { // islower() returns true iff C is the ASCII code for a lower-case letter; // we typecast the parameter C because islower() expects an int, not a // char to be passed to it if ( islower( (int) C) ) { // mild trick: if C is a lower-case letter then C - 'a' equals the // sequence number for C ('a' is at 0, 'b' is at 1, ...) cCount[ C - 'a' ]++; } } // print out how many occurrences of each lower-case letter we found: for ( int i = 0; i < NUMLWRCASE; i++) { // mild trick: 'a' + i will be the ASCII code for the // i-th lower-case letter; we typecast that to a char for // printing printf("%c: %d\n", (char)('a'+i), cCount[i]); } return 0; }