1

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.

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

chqrlie
  • 131,814
  • 10
  • 121
  • 189
vale383
  • 73
  • 6
  • 1
    Also see: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – kaylum Jun 09 '22 at 21:27

2 Answers2

2

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
1

strcmp requires a string. A string is a NUL terminated sequence of characters. But &ch is a pointer to a single character and is not a string.

Do char compare instead: if (ch == ':')

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • Hi! Yes I had just modified it to strcmp, but my first attempt was with `if (ch == ':')` as you say and still didn't get into the if statement. – vale383 Jun 09 '22 at 21:30
  • That would be a different issue. Please post a new question with that code. But for starters it would be good for you to do basic debugging. Run your program in a debugger and check the `ch` value to see if it is getting the values you expect, including the `':'`. – kaylum Jun 09 '22 at 21:41
  • Detail: In C, `ch == ':'` is an `int` compare. – chux - Reinstate Monica Jun 09 '22 at 21:50