Creating files through the racket

How can I use Racket to create a file to be able to store and edit user-entered data or a high score for example. I've read some of the documentation and haven't found a clear answer on how to do this.

+3


source to share


2 answers


There are some simple functions for reading and writing a file in the library 2htdp/batch-io

: http://docs.racket-lang.org/teachpack/2htdpbatch-io.html . They are somewhat limited in that they only access a file 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 (\ n means newline character) and then



(read-lines "highscore.txt")

      

to return the lines of the file as a list of lines.

+5


source


The Rocket Handbook has a chapter on Getting In and Out. the first section explains reading and writing files with examples. It says:

Files. The function open-output-file

opens the file for writing and open-input-file

opens the 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 the file already exists, it open-output-file

raises a default exception. Put an option like #:exists 'truncate

either #:exists 'update

overwrite or update the file:

etc.

+4


source







All Articles