Search code examples
ccharactertext-filescountertoupper

Counting Character usage in text file? C


Hi,
I need to count the usage of alphabetical characters in some plain text file. This is what i have came with. Basically just run through the text file and compare each character with the ASCII value of specific searched character.
When I run it, all I can see is just the first printf() string and just error of terminated status when I close the console.
I do have a text.txt file in same folder as the .exe file but I can't see anything.

Not sure if just my syntax is bad or even semantics.
Thx for help! :-)

#include <stdio.h>
#include <stdlib.h>
#define ASCIIstart 65 
#define ASCIIend 90

void main(){
    FILE *fopen(), *fp;
    int c;
    unsigned int sum;

    fp = fopen("text.txt","r");

    printf("Characters found in text: \n");

    for (int i = ASCIIstart; i <= ASCIIend; i++){
        sum = 0;
        c = toupper(getc(fp));
        while (c != EOF){
            if (c == i){
                sum = sum++;
            }
            c = toupper(getc(fp));
        }
        if (sum > 0){
            printf("%c: %u\n",i,sum);
        }
    }
    fclose(fp);
}

Solution

  • Rewind the pointer to the beginning of the file at the end of your for loop?

    This has been posted before: Resetting pointer to the start of file

    P.S. - maybe use an array for your output values : int charactercount[pow(2,sizeof(char))] so that you don't have to parse the file repeatedly?

    edit: was missing pow()