Alex Alex - 1 year ago 80
C Question

Q: How to compare char from text file in C?

So I want to be able to perform a check in where I compare the first character of the input file to a certain character (lets say * in this case) and then print "Hello world" if they do NOT match.

I am able to read in from the file. But strcmp() is not letting me compare the input file character and my declared character.

int main(void)
FILE *file = fopen("text.txt", "r");

char c;
char compare[] = "*"

c = fgetc(file);
compare = strcmp(c,compare); //Something is wrong here I think.
printf("result: %d \n", compare);
while (c != EOF);
return 0;

Answer Source

strcmp does not compare a character, it's a loop that compares two character arrays until there's a difference between them or both strings terminate with the null character at the same time.

if you want to compare two characters what you want to do is compare the two chars directly as in

char * string1 = "string1";
char * string2 = "string2";
if (string1[0] != string2[0])
    puts("hello world");

or in your case

if (c != compare[0])
    puts("hello world");

but since your compare is only one character and you want to only compare 1 character anyways you would be better off just declaring it as a char such as by doing

char compare = '*';
if (c != compare) 
   puts("hello world");