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.
>Solution :
There are multiple problems in your code:
-
chmust be defined asintto handleEOFreliably. -
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&chis not a C string. You should usech == ':'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;
}