简体   繁体   中英

Newline, EOF and feof() aren't acknowledged

I have a function that does the following:

ssize_t headache(char **lineptr, size_t *n, FILE * stream)
{
    if(lineptr != NULL)
    {
            free(*lineptr);
    }
    size_t  len     = 0,
            last    = 0;
    char *  buf     = NULL;
    int c;

    do
    { 
            last = len;
            ++len;
            buf = realloc(buf,len);
            c = fgetc(stream);
            buf[last] = (char)c;
            printf("%i\t%x\t%c\n", last, buf[last], buf[last]);
    }
    while(!feof(stream) || c != '\n');
    *n = strlen(buf);
    *lineptr = buf;
    return len;
}

headache is always called headache(&lineptr,&n,stream) where

char * lineptr = NULL;
size_t n = 0;
FILE * stream;

The do{}while(); loop will never acknowledge a newline or EOF, meaning that it will continue in infinity. I don't understand why is it ignoring EOF and '\\n'. Can someone please tell me what did I do wrong?

while(!feof(stream) || c != '\n');

will loop again unless both conditions evaluate to false. You want to exit the loop when you either receive EOF or \\n so should use && instead

while(!feof(stream) && c != '\n');

Your issue is with

while(!feof(stream) || c != '\\n')

this is because using || (or) you have to make both conditions false for it to stop execution. There are inputs that would make your while loop never end. this is a test input vs. this is a test input\\n .

If you are running this as stdin as your file* compare what happens when you run it with you typing a message and pressing enter and you typing a message and pressing control-d (which is EOF in a terminal)

As stated by simonc you need the && operator which only requires one of the conditions to be false for it to stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM