9.13 Closing a file. 4tH 4tH Forth compiler
إعلان
إعلان
CHAPTER 9. CHARACTER SEGMENT
The output of this program is:
This is written to screen
This is written to disk
105
Note that files are always opened in binary mode. If you’re a Microsoft user and you worry about your text files, don’t. 4tH is much smarter than that as you will learn later on.
9.13
Closing a file
There is usually no need to close any files. When you quit the program all files are closed.
It seems like there is no need at all to close files manually, but that is a mistake.
If you want to open a file for reading to which you’ve just written, you will find it doesn’t work. Of course, you can open a file only once.
No, there is a word which closes either the input- or the output-file, using the same read/writeflags. You’ve already seen it, it is called ’CLOSE’. When you close an active file, the input
(or output) is redirected to the keyboard (or screen).
9.14
Writing text-files
Writing text to a file is just as easy as writing text to screen. Open the file, redirect the output, and write like you would write to the screen: file OutFile s" outfile.dat" output open error?
abort" File could not be opened" to OutFile
\ value for file
\ put the filename on the stack
\ add the modifier
\ open the file
OutFile use
." This is written to disk" cr
\ write to file
That’s all! Note that if you execute your program on a Microsoft Operating System, it will write a Microsoft text file. If you do so on a Unix Operating System, it will write a Unix text file. If you want to override that you’ll have to issue the end-of-line sequences yourself using ’EMIT’.
9.15
Reading text-files
Reading text-files is pretty straightforward. You don’t even have to open a file in text-mode contrary to other languages. Just open the file and call ’REFILL’ until it signals end-of-file
(EOF):
\ Example program. It reads a file line by line
\ and prints it to the screen.
file InFile s" readln.4th" input open error?
abort" Could not open file" \ open file
تنزيل
إعلان