Hello, I receive the following error when compiling my program.
p8.c: In function `main':
p8.c:20: warning: passing arg 2 of `CountCharacter' from incompatible pointer type
I can see the problem is that I'm not passing the type of data I think I am. I basically want to pass a command line argument which is a filename to my function.
My understanding is that when I call CountCharacter(TargetChar, argv[i]), argv[i] is the address of where the filename string begins. Please help me out.
#include <stdio.h>
#include <stdlib.h>
int CountCharacter(char, char []);
int main(int argc, char *argv[])
{
char TargetChar;
int i;
if(argc < 2 || strlen(argv[1]) != 1)
{
printf("Usage: %s character [file1]...\n", argv[0]);
exit(1);
}
TargetChar = argv[1][0];
if(argc == 2)
printf("File: %s Character: %c Number: %d\n", "stdin", TargetChar, CountCharacter(TargetChar, stdin));
else
{
for(i = 2; i < argc; i++)
printf("File: %s Character: %c Number: %d\n", argv[i], TargetChar, CountCharacter(TargetChar, argv[i]));
}
return 0;
}
int CountCharacter(char TargetChar, char file[])
{
FILE *fp;
int Num = 0, Ch;
if(strcmp(file, "stdin"))
if((fp = fopen(file, "r")) == NULL)
{
printf("Can't open file %s for read\n", file);
return -1;
}
while((Ch = fgetc(fp)) != EOF)
{
if(Ch == TargetChar)
Num++;
}
if(fclose(fp) != 0)
printf("Error closing file %s\n", file);
return Num;
}