Reputation: 33
I am reading one line from a file which contains on the first line the word "hello". And then I am comparing it with "hello" using strcasecmp, however it is telling me it is still different
char *line = NULL;
size_t len = 100;
printf("%s", argv[1]);
FILE * fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("empty\n");
exit(0);
}
getline(&line, &len, fp);
if (strcasecmp(line, "hello") == 0) {
printf("same");
}
Upvotes: 0
Views: 3190
Reputation: 16540
this is from the man page for getline()
getline()
reads an entire line from stream, storing the address of the
buffer containing the text into *lineptr.
The buffer is null-terminated
and includes the newline character, if one was found.
Notice that part about including the newline character.
So, either limit the length of the comparison or better, trim the new line char, using something similar to:
char * newline = NULL;
if( NULL != (newline = strchr( line, '\n' ) )
{ // then newline found
*newline = '\0';
}
Upvotes: 0
Reputation: 52612
strcasecmp will only return 0 if the strings are the same (except for the case), not if the first string starts with the second string.
And getline reads the newline character at the end of the line, so if you type "hello" the string you get in "line" will be "hello\n".
Upvotes: 2