strcmp not working for fgets file read input string

I am reading words from file & need to search some specific words, below is my code

string read = malloc(50 * sizeof(char));

FILE* p = fopen("word","r");

while(fgets(read,50,p))
{
    printf("%s\n",read);
    if(strcmp(read,"apple") == 0)
     {
        printf("apple found\n");
        break;
     }
}

And sample file 'word' is as below,

$: more word

liol
apple
scizzors
big
bang
mentalist
scapegrace
goat
goti

Why is strcmp not working in this case, printf can print string read, so char pointer is working fine.

Answers


The fgets() function, in most circumstances, retains the newline at the end of the line. Hence yourtext\n will not compare equal to yourtext. You would have noted this with one of my favorite tricks for checking strings:

printf ("[%s]\n", read);

The presence of a newline before the closing ] would have immediately alerted you to the problem, or at a minimum raised an eyebrow.

If you want to strip a newline off before comparing, you can do something like:

int ln = strlen (read);
if ((ln > 0) && (read[ln-1] == '\n'))
    read[ln-1] = '\0';

Alternatively, you could skip that and just do:

if (strcmp (read,"apple\n") == 0)

It's not necessarily elegant but, if you don't need to use the word for anything other than that comparison, it'll be just fine.

However, you may then need to worry about the last line in the file in case it has no newline at the end of it so maybe it's better to use the newline-removing code above.


To search for a specific string in the line, rather than match the entire line, strncmp (which searches for n characters) can be used.

if (strncmp(read,"apple",strlen("apple")) == 0)
 {
    printf("apple found\n");
    break;
 }

Need Your Help

How to check which SQL query is so CPU intensive

odbc progress-4gl openedge progress-db

Is there any possible way to check which query is so CPU intensive in _sqlsrv2 process?

Fastest way to check Map for duplicate values?

dart

Given a Map, assignment, what is the fastest way to check if it contains any duplicate values in Dart? I am currently using a Set formed from the Map's values and checking its length against the