2010-11-15 29 views
4

Quelqu'un peut-il me diriger vers des exemples d'opérations d'E/S de base dans Scheme?Opérations d'E/S sur fichier - schéma

Je veux juste essayer les opérations de base de lecture/écriture/mise à jour sur un fichier. Il est difficile de ne pas avoir les ressources appropriées pour apprendre.

Répondre

12

La meilleure façon de lire les fichiers/écriture dans un schéma conforme R5RS est:

;; Read a text file 
(call-with-input-file "a.txt" 
    (lambda (input-port) 
    (let loop ((x (read-char input-port))) 
     (if (not (eof-object? x)) 
      (begin 
      (display x) 
      (loop (read-char input-port))))))) 

;; Write to a text file 
(call-with-output-file "b.txt" 
    (lambda (output-port) 
    (display "hello, world" output-port))) ;; or (write "hello, world" output-port) 

Scheme a cette notion de ports qui représentent les périphériques sur lesquels les opérations d'E/S peuvent être effectuées. La plupart des implémentations de Scheme associent call-with-input-file et call-with-output-file avec des fichiers de disque littéraux et vous pouvez les utiliser en toute sécurité.

1

S'il vous plaît voir le message suivant si vous travaillez avec un schéma conforme r5rs:

R5RS Scheme input-output: How to write/append text to an output file?

La solution présentée, il est comme suit:

; This call opens a file in the append mode (it will create a file if it doesn't exist) 
(define my-file (open-file "my-file-name.txt" "a")) 

; You save text to a variable 
(define my-text-var1 "This is some text I want in a file") 
(define my-text-var2 "This is some more text I want in a file") 

; You can output these variables or just text to the file above specified 
; You use string-append to tie that text and a new line character together. 
(display (string-append my-text-var1 "\r\n" my-file)) 
(display (string-append my-text-var2 "\r\n" my-file)) 
(display (string-append "This is some other text I want in the file" "\r\n" my-file)) 

; Be sure to close the file, or your file will not be updated. 
(close-output-port my-file)