|
Wil Baden 2000-08-21
SPONGE requires
SLURP
Only the words of the CORE word set have been redefined, as output redirection should be done by the system.
OUTPUT-REDIRECTION
( -- )
ALSO OUTPUT-REDIRECTION ... PREVIOUS
ONLY FORTH DEFINITIONS ALSO OUTPUT-REDIRECTION ...
ONLY FORTH DEFINITIONS,
'OUTPUT
( -- addr)
'OUTPUT to 0 on an abort or error. Not having
that you may want to use 'OUTPUT OFF at the beginning of
a function that's going to redirect output.
>OUTPUT
( n -- )
'OUTPUT, do nothing. Otherwise cease output to the
file, and set up for new redirection. Use n equal 0 to
terminate output redirection.
VARIABLE 'OUTPUT 0 'OUTPUT ! \ Should be user variable.
S" /COUNTED-STRING" ENVIRONMENT? 0= [IF] 255 [THEN]
CONSTANT /COUNTED-STRING
VOCABULARY OUTPUT-REDIRECTION
ONLY FORTH ALSO OUTPUT-REDIRECTION DEFINITIONS
CREATE OUTBUFFER /COUNTED-STRING 1+ CHARS ALLOT \ Should be user array.
0 OUTBUFFER C!
: CR ( -- )
'OUTPUT @ IF
OUTBUFFER COUNT 'OUTPUT @ WRITE-LINE FILE-CHECK
0 OUTBUFFER C!
ELSE CR THEN ;
: MORE ( n addr -- addr )
TUCK C@ + /COUNTED-STRING > IF CR THEN ;
: TYPE ( str len -- )
'OUTPUT @ IF DUP OUTBUFFER MORE APPEND
ELSE TYPE THEN ;
: EMIT ( char -- )
'OUTPUT @ IF 1 OUTBUFFER MORE APPEND-CHAR
ELSE EMIT THEN ;
: SPACE ( -- ) BL EMIT ;
: SPACES ( n -- )
'OUTPUT @ IF
0 MAX /COUNTED-STRING MIN
DUP OUTBUFFER MORE ( n addr)
2DUP COUNT + SWAP BL FILL
C+!
ELSE SPACES THEN ;
: . ( n -- ) (.) TYPE SPACE ;
: U. ( u -- ) 0 <# #S #> TYPE SPACE ;
: ." ( "string<single-quote>" -- )
POSTPONE S"
STATE @ IF POSTPONE TYPE
ELSE TYPE
THEN ; IMMEDIATE
ONLY FORTH DEFINITIONS ALSO OUTPUT-REDIRECTION
: >OUTPUT ( n -- )
DUP 'OUTPUT @ = IF DROP EXIT THEN
'OUTPUT @ IF
OUTBUFFER C@ IF CR THEN
THEN
0 OUTBUFFER C! \ Be sure.
'OUTPUT ! ;
ONLY FORTH DEFINITIONS
Wil Baden 2000-08-26
From JARGON File
sponge
A sponge can be written using SLURP with output redirection.
SPONGE
( "file-name" -- src length file-id )
For an example of a sponge, see DETAB.
Program Text 4 CREATE Name-Holder 64 CHARS ALLOT
: SPONGE ( "file-name" -- src length file-id )
BL WORD COUNT Name-Holder PLACE ( )
Name-Holder COUNT R/O OPEN-FILE FILE-CHECK ( file-id)
DUP SLURP ROT CLOSE-FILE FILE-CHECK ( src length)
Name-Holder COUNT DELETE-FILE DROP
Name-Holder COUNT W/O CREATE-FILE FILE-CHECK
( src length file-id)
;
Another approach is slurp file, delete and create temporary file, and redirect output to temporary file. Then close temporary file, and if successful, delete original file and rename the temporary file as the original file.