Reputation: 13
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?
Upvotes: 1
Views: 566
Reputation: 41
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.
Upvotes: 0
Reputation: 42175
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');
Upvotes: 3