Huh!!How shall I put the whole thing in a clear question!!Let me try:
I know that the files opened using fopen()
are buffered into memory.We use a buffer for efficiency and ease.During a read from the file, the contents of the file are first read to the buffer,and we read from that buffer.Similarly,in a write to the file, the contents are written to the buffer first ,and then to the file.
But what with fseek()
,fsetpos()
and rewind()
dropping the effect of the previous calls to ungetc()
? Can you tell me how it is done?I mean,given we have opened a file for read and it is copied into the buffer.Now using ungetc()
we've changed some characters in the buffer.Here is what I just fail to understand even after much effort:
Here's what said about the
ungetc()
--"A call to fseek, fsetpos or rewind on stream will discard any characters previously put back into it with this function." --How can characters already put into the buffer be discarded?One approach is that the original characters that were removed are "remembered",and each new character that was put in is identified and replaced with original character.But it seems very inefficient.The other option is to load a copy of the original file into buffer and place the file pointer at the intended position.Which approach of these two does fseek, fsetpos or rewind take to discard the characters put usingungetc()
?For text streams,how does the presence of unread characters in the stream,characters that were put in using
ungetc()
, affect the return value offtell()
?My confusion arise from the following line aboutftell()
andungetc()
from this link aboutftell
(SOURCE)
"For text streams, the numerical value may not be meaningful but can still be used to restore the position to the same position later using fseek (if there are characters put back using ungetc still pending of being read, the behavior is undefined)."
- Focusing on the last line of the above paragraph,what has
pending of being read
got to do with a "ungetc()-obtained" character being discarded? Each time we read a character that was put into the stream usingungetc()
,is it discarded after the read?