diff options
author | Nami-Doc <vendethiel@hotmail.fr> | 2014-01-05 06:45:44 -0800 |
---|---|---|
committer | Nami-Doc <vendethiel@hotmail.fr> | 2014-01-05 06:45:44 -0800 |
commit | ffaaa44e7458d3e5fb88e624cb90c43a038de564 (patch) | |
tree | 12f8c090bbdb025fd031e15dc4efab0fc745c2d8 /racket.html.markdown | |
parent | 283f3d4089e566ead35fe6dae0a239ed9071007d (diff) | |
parent | 6801c7056d0e2d2eac269ff81a969c29775f6e4a (diff) |
Merge pull request #476 from cmpitg/master
[racket/en] Add input/output section for Racket
Diffstat (limited to 'racket.html.markdown')
-rw-r--r-- | racket.html.markdown | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/racket.html.markdown b/racket.html.markdown index adacd91d..eddc00bf 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -6,6 +6,7 @@ contributors: - ["th3rac25", "https://github.com/voila"] - ["Eli Barzilay", "https://github.com/elibarzilay"] - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] + - ["Duong H. Nguyen", "https://github.com/cmpitg"] --- Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. @@ -600,6 +601,45 @@ vec ; => #(1 2 3 4) ;; expected: positive? ;; given: -5 ;; more details.... + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 11. Input & output +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Racket has this concept of "port", which is very similar to file +;; descriptors in other languages + +;; Open "/tmp/tmp.txt" and write "Hello World" +;; This would trigger an error if the file's already existed +(define out-port (open-output-file "/tmp/tmp.txt")) +(displayln "Hello World" out-port) +(close-output-port out-port) + +;; Append to "/tmp/tmp.txt" +(define out-port (open-output-file "/tmp/tmp.txt" + #:exists 'append)) +(displayln "Hola mundo" out-port) +(close-output-port out-port) + +;; Read from the file again +(define in-port (open-input-file "/tmp/tmp.txt")) +(displayln (read-line in-port)) +; => "Hello World" +(displayln (read-line in-port)) +; => "Hola mundo" +(close-input-port in-port) + +;; Alternatively, with call-with-output-file you don't need to explicitly +;; close the file +(call-with-output-file "/tmp/tmp.txt" + #:exists 'update ; Rewrite the content + (λ (out-port) + (displayln "World Hello!" out-port))) + +;; And call-with-input-file does the same thing for input +(call-with-input-file "/tmp/tmp.txt" + (λ (in-port) + (displayln (read-line in-port)))) ``` ## Further Reading |