can we ungetc ?

Started by nigelbrown, December 22, 2003, 07:54:21 AM

Previous topic - Next topic

nigelbrown

In C programming sometimes to look ahead at the next file character a ch=getc(infile) is done and then if the logic requires that ch not be handled now a ungetc( ch, infile) is used to put the char back for later processing.

How feasible would it be to have the same facility available for (read-char

viz (unread-char ? I tried (write-char back into a file opened as update but that doesn't work. viz

> (set 'aFile (open "myfile.ext" "u"))

1

> (setq ch (read-char aFile))

97

> (write-char aFile ch)

1

> (setq ch (read-char aFile))

113

>



If it's not easy at the C source level for newlisp I'll try a getc & ungetc with defines or macros (anybody got such functions?).



I want getc/ungetc for a fairly 'no thinking please' C to newlisp port of a C program.



Regards

Nigel



Nigel

nigelbrown

#1
PS I believe Common Lisp has peek-char to let you look 1 char ahead into a stream - saves doing get then unget - instead doing a peek then a get if needed.



Nigel

Lutz

#2
Some 'unread-char' function is easy to implement, I will put it on the list.



BTW, I did the commandline switch to limit memory usage, that will be in the next development version.



Lutz

nigelbrown

#3
Thanks for the memories

usage check



Nigel

Lutz

#4
this is the definition of an 'unread-char':



(define (unread-char fle) (seek fle (- (seek fle) 1)))



it returns the decremented file position and is surprisingly fast compared with the 'read-char' on a 1.4Ghz Celeron and WinXP:



read-char => 1.8 micro seconds

unread-char => 2.6 micro seconds



Note, that the function will wrap around to the end of the file when the beginning (position 0) is reached.



Lutz