Danger
Danger

Reputation: 71

Create Files Through Racket

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.

Upvotes: 7

Views: 5944

Answers (2)

Ryan Culpepper
Ryan Culpepper

Reputation: 10643

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, and open-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.

Upvotes: 8

nadeem
nadeem

Reputation: 721

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.

Upvotes: 5

Related Questions