G
Grumfish
Is there a way to see the next character of an input file object without
advancing the position in the file?
advancing the position in the file?
Is there a way to see the next character of an input file object without
advancing the position in the file?
Warning, though: this is very iffy on windows unless you have opened the fileTo do this, you can do the following:
fin = file('myfile')
...
char = fin.read(1)
fin.seek(-1,1) # set the file's current position back a character
def peek(self, cnt):
data = self.read(cnt)
self.seek(cnt * -1, 1)
return data
def peekline(self):
pos = self.tell()
data = self.readline()
self.seek(pos, 0)
return data
[Bengt]
if you're going to seek/tell, best to do it in binary, and deal with the platform dependent EOLs.
Grumfish said:Is there a way to see the next character of an input file object without
advancing the position in the file?
seek() works perfectly with text-mode files as long as you only seek to
places given to you by tell(). So if Keith's peek() function had used
tell() and then seek()ed (sought()? back to that point like his
peekline() does, there would be no problem.
[Bengt]
Can you cite a C or C++ standard section that guarantees that seek/tell
will work that way in text mode? (I'm not saying there isn't one, but
I couldn't find one quickly ;-)
Thank you. It makes sense that you could retrieve and set an underlying binary position[Richie]seek() works perfectly with text-mode files as long as you only seek to
places given to you by tell(). So if Keith's peek() function had used
tell() and then seek()ed (sought()? back to that point like his
peekline() does, there would be no problem.
[Bengt]
Can you cite a C or C++ standard section that guarantees that seek/tell
will work that way in text mode? (I'm not saying there isn't one, but
I couldn't find one quickly ;-)
ANSI C, ISO/IEC 9899:1990, section 7.9.9.2: "For a text stream, either
offset shall be zero, or offset shall be a value returned by an earlier
call to the ftell function on the same stream and whence shall be
SEEK_SET."
BTW, is there an ANSI C spec available free on line
(or an older, close-enough draft)?
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.