Read Write Text Files Swiftforth
How to Read and Write to text files using the Forth programming language
Words used in the video
Word | Description |
---|---|
CREATE-FILE | Creates a file and give you a fileid. |
WRITE-FILE | Takes the fileid and writes text to it. |
>SHELL | Sends a command to command prompt |
PAD | A scratch pad of memory |
OPEN-FILE | Open an existing text file and output its fileid. |
SLURP-FILE | Bring a text file into memory. |
CLOSE-FILE | Close a text file. |
How to create a simple text file using SwiftForth
\ This will create a text file called “testing.txt”
s" c:\testing.txt" r/w create-file
\ After you hit enter, 2 things will be left on the data stack
1128 0 <–Top
\ We don’t need the zero, so type in “drop” and remove it
1128 <–Top
\ Next we need some text to send to the text file
s" hello 123"
\ After you hit enter, your data stack should look like this
1128 4212948 9 <–Top
*Don’t worry if 4212948 isn’t the same. Every computer will show a different number
\ Type in ROT to get the stack in the correct order
ROT
4212948 9 1128 <–Top
\ Type in “WRITE-FILE” and hit enter
WRITE-FILE
\ Next to see your text file do this:
s" c\testing.txt" >shell
\ Close the file out
1128 CLOSE-FILE
Make sure to use close-file because leaving it open will cause some errors.
BONUS words used at end of video
: SLURP-FILE ( filename length – data-addr length ior )
R/O OPEN-FILE ?DUP IF 0 SWAP EXIT THEN
DUP >R MAP-FILE R> CLOSE-FILE DROP ;
: SLURP ( filename length – data-addr length )
SLURP-FILE ABORT" slurp failed" ;
: SPEW ( data-addr len filename len – )
R/W CREATE-FILE ABORT" spew failed" >R
R@ WRITE-FILE DROP R> CLOSE-FILE DROP ;