How do reading functions mark an end?
Hi all,
How does a reading function , eg scanf() or fgets(), mark the end of an input string(character)? with EOF , NULL ,'\0' , or '\n'?
Take a look at these these snippets, do they want to test the end of a stream? but in vc, NULL is defined as 0, and EOF is -1.......headache....
Code:
if (fgets(buf, sizeof(buf), stdin) != NULL)
Code:
while ((c = fgetc(fp)) != EOF)
so, how should i test the end of a stream?
any advice would be appreciated! thanks!
Much clearer, and more....
Thank you , it is much better now,
Can I understand it this way?
1.EOF is a negative value returned only by a read function.
2.'\0' is set after the last character to mark the end of a string. so we use '\0' to determine
the end of a stream.
3.NULL is always recommanded to be used for pointers.
and NULL is always a return code of a function.
4. NULL isn't equal to '\0'.
is it right?
and more questions..
a pice of orginal text from "Why it's bad to use feof() to control a loop"
Code:
most read functions will set EOF once they've read all the data, and then performed a final
read resulting in no data, only EOF
I am a little confusing about it,
Code:
most read functions will set EOF once they've read all the data,
set EOF means set '/0'?
Code:
and then performed a final read resulting in no data, only EOF
after haveing set EOF, why they read for a final one, to verify that all data was read?
Code:
i = 0;
while (!feof(fp))
{
fgets(buf, sizeof(buf), fp);
printf ("Line %4d: %s", i, buf);
i++;
}
Code:
as the program goes through the loop to get the last line of data, fgets() works normally,
without setting EOF .
as mentioned above, it should set EOF right after getting all data,why here it goes
without setting EOF?
Code:
and we print out the data. The loop returns to the
top, and the call to feof() returns FALSE, and we start to go through the loop again. This
time, the fgets() sees and sets EOF
why now (set EOF)?
Code:
but thanks to our poor logic, we go on to
process the buffer anyway, without realising that its content is now undefined (most likely
untouched from the last loop).
looking forward answers, thanks a lot:)
what about stream and string?
what about stream and string?
when we use
Code:
fgets(buf, sizeof(buf), stdin);
what it get from stdin is a stream or a string?
what stored in buf is a string or a string?
;)