2.15 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.

Reading blocks of data usually means defining buffers. If maintainabil- ity is an issue, define a constant for the sizes of these buffers. You cannot only use this constants when defining buffers, but also when calling 'ACCEPT'.

Furthermore, 'ACCEPT' returns the number of characters actually read. If this value is compared to the number of characters we actually wanted to read, we can determine whether a reading error or EOF occured:

     1024 constant bufsize           \ actual buffersize
     bufsize string buffer           \ define buffer

     64 string filename              \ define string
     " infile.dat" filename copy     \ make filename

     input open
     if                              \ open input file
           input file                \ redirect input

           begin                     \ using bufsize
                bufsize         ( n1)
                buffer over     ( n1 a n1)
                accept          ( n1 n2)
                <>              ( f) \ make EOF flag
           until                     \ until EOF
     else                            \ issue error message
           ." File could not be opened" cr quit
     then

Note that "BUFFER" is actually not a string, but a chunk of memory. But since a character in 4tH takes up a single address-unit (=byte), raw chunks of memory are allocated in the Character Segment. This is not an uncommon practice in both Forth and C.