can we ungetc ?

For the Compleat Fan
Locked
nigelbrown
Posts: 429
Joined: Tue Nov 11, 2003 2:11 am
Location: Brisbane, Australia

can we ungetc ?

Post by 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
Posts: 429
Joined: Tue Nov 11, 2003 2:11 am
Location: Brisbane, Australia

Post by nigelbrown »

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
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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
Posts: 429
Joined: Tue Nov 11, 2003 2:11 am
Location: Brisbane, Australia

Post by nigelbrown »

Thanks for the memories
usage check

Nigel

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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

Locked