Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Files Through Racket

Tags:

scheme

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.

like image 884
Danger Avatar asked Mar 25 '12 02:03

Danger


2 Answers

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.

like image 160
Ryan Culpepper Avatar answered Nov 15 '22 08:11

Ryan Culpepper


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.

like image 32
nadeem Avatar answered Nov 15 '22 08:11

nadeem