How would I use Racket to create a file to be able to store and edit user-inputted data, or, for example, a high score. I've read through some of the documentation and haven't found a clear answer on how to do this.
The Racket Guide has a chapter on Input and Output. The first section explains reading and writing files, with examples. It says
Files: The
open-output-file
function opens a file for writing, andopen-input-file
opens a file for reading.
Examples:
> (define out (open-output-file "data"))
> (display "hello" out)
> (close-output-port out)
> (define in (open-input-file "data"))
> (read-line in)
"hello"
> (close-input-port in)
If a file exists already, then
open-output-file
raises an exception by default. Supply an option like#:exists 'truncate
or#:exists 'update
to re-write or update the file:
and so on.
There are some simple functions for reading and writing a file in the 2htdp/batch-io
library: http://docs.racket-lang.org/teachpack/2htdpbatch-io.html . They are somewhat limited in that they access a file only in the same directory as the program itself, but you can do something like:
(require 2htdp/batch-io)
(write-file "highscore.txt" "Alice 25\nBob 40\n")
to write data to a file (the \n means a newline character), and then
(read-lines "highscore.txt")
to get back the lines of the file, as a list of strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With