We’ve discussed the “text files as blocks” in a previous post. As a recap, we store a text file in consecutive 1024byte blocks, with character 13 (CR) as the End Of Line (EOL), and pad to the end of the block with character 26 as the End Of File (EOF).
To implement this, I’ll add a feature called BLKFILE. Essentially, it’s a pointer to a Block number and offset, which is incremented on read or write of a character.
Low level words
In ROM, the following words are implemented:
BEGIN-BLKFILE ( blk offset -- )
Starts a new BLKFILE session and sets the current BLKFILE pointer to block number blk and offset.
END-BLKFILE ( -- blk' offset' )
Ends the current BLKFILE session, flushes any output, and returns the current block number and offset.
GETCH ( -- c )
Reads the character at the current BLKFILE pointer, increments the pointer, and returns the character. If the BLKFILE pointer offset reaches the end of the block, the next block is loaded.
GETCHARS ( c-addr u -- u )
Reads u number of characters from the current BLKFILE pointer, to buffer pointing at c-addr. The BLKFILE pointer is incremented, possibly crossing block boundaries. This returns the number of characters read.
PUTCH ( c -- )
Writes character c to the current BLKFILE pointer, increments the pointer, possibly crossing block boundaries. The block is UPDATEd
PUTCHARS ( c-addr u -- u )
Writes the buffer pointed to at c-addr (u bytes) to the current BLKFILE, incrementing the pointer and possibly crossing block boundaries. The affected blocks are UPDATEd.
High-level words
With the Low-level words implemented in ROM, it should then be simple enough to implement a Higher-level BLKFILE wordset, which work like the forth standard file-access wordset:
OPEN-BLKFILE ( blk fam -- blkfile-id ior )
CLOSE-BLKFILE ( blkfile-id -- ior )
READ-BLKFILE ( c-addr u blkfile-id -- u ior )
READLINE-BLKFILE ( c-addr u blkfile-id -- u f ior )
WRITE-BLKFILE ( c-addr u blkfile-id -- ior )
WRITELINE-BLKFILE ( c-addr u blkfile-id -- ior )
BLKFILE-POSITION ( blkfile-id -- blk offset ior )
REPOSITION-BLKFILE ( blk offset blkfile-id -- ior )