Reading File

I'm trying to write a code for a class that takes a filename and target character from command line and counts the number of times the target character appears in the file. Every time I run the program, it gives returns half the number of characters that are actually are. Why is this happening?

[code]
#include <stdio.h>
#include <string.h>

int char_count(const char *filename, char target_char);

int main(int argc, char **argv){
if(argc != 3){
printf("./file_char_count <filename> <target character>\n");
return 1;
}
if(strlen(argv[2]) > 1){
printf("Argument should only contain one character\n");
return 2;
}
if(char_count(argv[1], *argv[2]) == -1){
printf("The file does not exist\n");
return 3;
}
else{
printf("%i\n", char_count(argv[1], *argv[2]));
}
return 0;
}

int char_count(const char *filename, char target_char){
FILE *fp = fopen(filename, "r");
int count = 0;
if (fp == NULL){
return -1;
}
else{
while(getc(fp)!= EOF){
if(getc(fp) == target_char){
count = count + 1;
}
}
return count;
}
}
[code]
The problem is in these lines:
1
2
3
while(getc(fp)!= EOF)
{
  if(getc(fp) == target_char)

You read two chars but process only one so basically you skip every second char.
Thank you!
Hello emma if you wish to learn C++ properly why not check out my course: https://www.udemy.com/learn-cpp-from-scratch/?couponCode=CPPFORUM I teach you all the way from basics to more advanced concepts. 50% off for today only.
Topic archived. No new replies allowed.