stuntpenguin007
stuntpenguin007

Reputation: 37

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)

Upvotes: 1

Views: 2156

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84632

Your use of feof is not needed in this situation. You are using getline and strcmp to test the line. Use the return from getline to test whether to continue reading. A correct implementation would be similar to:

while (getline(&input, &len, *stream) != -1)
{
    if(strcmp (input, "section1\n") == 0)
    {
        printf("End of section\n");
        found = 1;
        break;  /* if you want to terminate read when found=1 */
    }
}

To eliminate the problem with dangling newlines at the end of each line read, simply remove them. getline makes this quite simple as it returns the number of characters actually read -- eliminating the need to call strlen. Simply capture the return of getline in a variable, and remove the newline (or both carriage return & newline if using DOS line ends) as follows:

ssize_t nchr = 0;   /* number of characters actually read */

while ((nchr = getline (&input, &len, *stream)) != -1)
{
    /* strip trailing '\n' or '\r' */
    while (nchr > 0 && (input[nchr-1] == '\n' || input[nchr-1] == '\r'))
        input[--nchr] = 0;
    ...

Upvotes: 1

chux
chux

Reputation: 154198

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().

Upvotes: 5

Related Questions