There are no special words to read from or write to a file. You can use all the words you used for keyboard-input and screen- output.
But if you open a file and do some I/O you will notice nothing has changed. Of course not. You should be able to determine whether you write to a file or to the screen. There are special words to do just that:
64 string filename " outfile.dat" filename copy output open \ open the file 0= if \ error if not open ." File could not be opened" cr quit then output file \ write to file ." This is written to disk" cr output tty \ write to screen ." This is written to screen" cr
After you've opened the file, the program will still write to the screen. When 'FILE' executes, all output will be redirected to the file. When 'TTY' executes, all output will go to the screen again, but the output-file will not be closed! Both words take the same read/write-flags as 'OPEN'.
You can call 'FILE' or 'TTY' again and again, without closing or opening any files. Here is an example using an input-file:
64 string filename " outfile.dat" filename copy \ make filename output open \ open output file 0= if \ error if not open ." File could not be opened" cr quit then output file \ write to file ." This is written to disk" cr output tty \ write to screen ." This is written to screen" cr output close \ close file " outfile.dat" filename copy input open 0= if \ open input file ." File could not be opened" cr quit then input file \ read from disk tib dup 32 accept \ read 32 characters type \ write string to screen input tty \ read from keyboard input close \ close file
The output of this program is:
This is written to screen This is written to disk
Microsoft-users, note that files are opened in binary mode (no CR/LF translations). If you issue 'CR' the line will be terminated by a linefeed.