Reputation: 117
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.
Upvotes: 2
Views: 890
Reputation: 144740
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;
}
Upvotes: 3
Reputation: 14046
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 == ':')
Upvotes: 1