Count all occurrences of characters in a text file

advertisements

The following code snippet is intended to count all the symbols met in a file after text is entered, next step is counting the occurrences of all characters (For instance 'a' met 3 times, 'b' 0 times etc.). However when I compile the loop goes infinite and the counting is always 0. My question is if it could be fixed or rewritten in another way.

char type, c, text[100]; counts[100];
int count=0, i;

while((type=getchar())!=EOF) {
    fputc(type, f); count++;
}

printf("Symbols found: %d", count-1);
rewind(f);

while(fscanf(f, "%s", &text)) {
    for (i = 0; i < strlen(text); i++) {
        counts[(text[i])]++;
        printf("The %d. character has %d occurrences.\n", i, counts[i]);
    }
}


You can build your histogram as you read the input. The return value from getchar() is an int, not a char, since it has to represent EOF in addition to the 256 char values. Once the histogram has been built, you can iterate over the buckets and print them. Here, I have assumed that all 256 char values are possible, and included code to display unprintable characters in hex notation.

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

int main(int argc, char **argv)
{
    int c;
    int i;
    int histogram[256];
    int total;

    memset(histogram, 0, sizeof(histogram));
    total = 0;

    while ((c = getchar()) != EOF) {
        histogram[c]++;
        total++;
    }

    printf("Symbols found: %d\n", total);

    for (i = 0; i < 256; i++) {
        if (histogram[i]) {
            char repr[5];
            sprintf(repr, isprint(i) ? "%c" : "\\x%02x", i);
            printf("The '%s'. character has %d occurrences.\n", repr, histogram[i]);
        }
    }

    return 0;
}