Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count occurrences of character in file -C

I have a text file with this format

Hello:Dad
How:Are
You:Today

I want to count how many times the colon appears in the file, for that I’m doing this function:

int NumColon(char txt[]) {
    FILE *fp = fopen(txt, "r");

    if (fp == NULL) {
        exit(1);
    }

    int count = 0;
    char ch;

    while (!feof(fp)) {
        ch = getc(fp);
        if (strcmp(&ch, ":") == 0) {
            count++;
        }
    }

    return count;
}

But when I print the value of the variable count it is on zero. However, if I do a fprint("%s", &ch); inside the while loop but before the if statement, I can clearly see that in certain moments the character obtained it’s : so I don’t understand what is happening and why isn’t it getting inside the if statement of the loop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: I’ve also tried using if (ch == ':') but still cannot get into the if statement.

>Solution :

There are multiple problems in your code:

  • ch must be defined as int to handle EOF reliably.

  • while (!feof(fp)) is incorrect. Learn Why is “while ( !feof (file) )” always wrong? You should instead write:

    while ((ch - getc(fp)) != EOF)
    
  • strcmp(&ch, ":") is incorrect because &ch is not a C string. You should use ch == ':' instead.

  • you forget to close the file, causing a resource leak.

Here is a modified version:

int NumColon(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        return -1;
    }
    int count = 0;
    int c;
    while ((c = getc(fp)) != EOF) {
        count += (c == ':');
    }
    fclose(fp);
    return count;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading