Some examples are useful here. The following code segment types the contents of CALC.APP to the screen: Note: The code down to >here is assumed for all of the examples in this section.
( file.fth )
-1 constant true
0 constant false
variable fin
variable inbuf 100 allot
: list.file ( --- )
" calc.app" READ fopen fin !
begin
inbuf 80 fin @ fgets
if ( Not EOF )
inbuf count type
false
else ( EOF )
true
then
until
fin @ fclose
;
list.file opens the file, calc.app, for READ access. fopen expects the filename address on the stack. The " compiles the filename into the dictionary. fopen returns the file descriptor, which is saved in fin. The file descriptor should really be checked for error before continuing. The loop reads each line into inbuf and types the contents to the screen. fgets returns the length of the line or zero at end of file. The loop exits on end of file and closes the file.
The next example copies a file, one character at a time. The code assumes the same variables etc from the previous example exist.
-1 constant true
0 constant false
variable fout
variable fin
variable inbuf 100 allot
: copy.file
" calc.app" READ fopen fin !
" xxx.xxx" WRITE fopen fout !
begin
fin @ fgetc
dup
true = 0=
if ( not eof )
fout @ fputc drop
false
else
true
then
until
fin @ fclose
fout @ fclose
;
Opening the files is identical to the first example. The loop reads a
character from the input file using fgetc and tests for end of file.
Each character is written to the output file by fputc.
Add example using fputline, etc - block to text file converter would be nice...
File manipulation in Until is implemented indirectly via C I/O functions. The primary difference is passing arguments on the stack to the primitive, which in turn calls the corresponding C function.