Search code examples
cgetlinestrcmp

C - getline() and strcmp() issue


I am having an issue where I can not find a specific word in a file with strcmp() when using getline.

My file looks something like this:

Word1
Word2
Word3
section1
Word4

This is the code I have right now:

while(found == 0)
{
    getline(&input, &len, *stream);
    if (feof(*stream))
        break;

    if(strcmp(input, "section1\n") == 0)
    {
        printf("End of section\n");
        found = 1;
    }
}

strcmp() never returns 0 though. Any insight would be greatly appreciated!

Made an edit to the code. I transferred it incorrectly.

Solution from the comments: I need to add \r to the string being compared

if(strcmp(input, "section1\r\n") == 0)

Solution

  • Remove potential end-of-line character(s), then compare.

    getline(&input, &len, *stream);
    input[strcspn(input, "\r\n")] = 0;
    if(strcmp(input, "section1") == 0)
    {
        printf("End of section\n");
        found = 1;
    }
    

    Notes: With getline(), the buffer is null-terminated and includes the newline character, if one was found. Wise to check the return value from getline().