Why does this code always print "not matched"?

73 views Asked by At
#include <stdio.h>

int main(int argc, char const *argv[])
{
    FILE *ls = popen("tmp.sh", "r");
    char char_array[256];
    while (fgets(char_array, sizeof(char_array), ls) != 0) {
       //NOP
    }
    char *ptr_somechar = &char_array[0];
    char *pointer = "high";
    if (strcmp(pointer, ptr_somechar) == 0) 
    { 
        printf("%s\n", "match");
    } else 
    { 
        printf("%s\n", "not matched");
    }
    pclose(ls);
    return 0;
}

I want to compare the output with the line. tmp.sh returns a "high". Why does this code always print "not matched"?

1

There are 1 answers

0
haccks On BEST ANSWER

It seems that the string "high" in file is followed by a newline character and fgets reads that \n too. You need to remove that character before comparison.