9.17 Reading binary files. 4tH 4tH Forth compiler
Publicité
Publicité
CHAPTER 9. CHARACTER SEGMENT 106 to InFile
InFile use begin refill while
0 parse-word type cr repeat
\ save handle
\ read from file
\ read a line
\ while EOF not found
\ parse the entire line
\ print it
\ terminate line
\ read next line
You will find that if you run this program, it will print itself to the screen.
’REFILL’ will return a non-zero value if EOF was not detected. By using the word ’0=’ you can invert this value. Finally, it will read Unix ASCII-files as well as DOS ASCII-files, no matter where your program is executed.
9.16
Reading long lines
The TIB is only /TIB characters long. If you read a line that is longer than that, only /TIB - 1 characters are read. The rest of the line is read when you invoke ’REFILL’ again. Although you don’t lose any information that way, it might not be what you want. Fortunately, you can define your own TIB:
2048 constant /mytib
/mytib string mytib mytib /mytib source!
\ length of your TIB
\ define your own TIB
\ tell the system about your TIB
The next time you invoke ’REFILL’, it will use your TIB instead of the system TIB, so it will now read lines up to 2047 characters. ’SOURCE!’ takes an address/count pair and makes it the current TIB. So if you want to use the system TIB again you issue: tib /tib source!
And if you have forgotten which TIB you’re using try this: source . . cr
’SOURCE’ will return the address/count pair of the TIB you’re currently using. In fact, this definition does absolutely nothing:
: doesnothing source source! ;
For the simple reason that it reassigns the TIB it is already using.
9.17
Reading binary files
If you process binary files, you won’t get far reading it line by line. You want to read chunks of data. 4tH can do that too by using ’ACCEPT’. You feel there must be a catch, since ’ACCEPT’ terminates strings automatically. Well, there isn’t. When ’ACCEPT’ does not read from the keyboard, it won’t add that extra byte.
Télécharger
Publicité