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.


source to share

2 answers

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

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



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.

> (define out (open-output-file "data"))
> (display "hello" out)
> (close-output-port out)
> (define in (open-input-file "data"))
> (read-line in)
> (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:




All Articles