how to write alike display (printf) to file in scheme?

别说谁变了你拦得住时间么 提交于 2019-12-25 06:07:07

问题


Using TinyScheme.

I'm writing my code to file (solved it in 50% here: How to write to a file in tinyscheme?) with:

(with-output-to-file "biophilia.c"
  (lambda ()
    (write code)
    ))
; and segmentation fault comes here

but it writes my code with "" qotes and \n\r as is so it doesn't translate it to newline.

I need to write code like it looks with (display code)

in example in racket docs there is printf but seems like TinyScheme implementation got no printf, maybe I need to discover (add code of it) printf?


回答1:


You could try:

(call-with-output-file "biophilia.c" 
    (lambda (port) 
        (write-string code port)))

Provided "code" is a string. It will remove any escapes, and write it as plain text.




回答2:


Found solution, the only fix is ex-hanged put-char to write-char

  (define assert
    (lambda (aa msg)
      (if (null? aa)
    #t
    (if (not (car aa))
      (error msg)
      (assert (cdr aa) msg))))) 

 (display "define fprintf\n\r")
(define (fprintf port f . args)
   (let ((len (string-length f)))
     (let loop ((i 0) (args args))
       (cond ((= i len) (assert (null? args)))
         ((and (char=? (string-ref f i) #\~)
           (< (+ i 1) len))
          (dispatch-format (string-ref f (+ i 1)) port (car args))
          (loop (+ i 2) (cdr args)))
         (else
          (write-char (string-ref f i) port)
          (loop (+ i 1) args))))))

(display "define printf\n\r")
(define (printf f . args)
   (let ((port (current-output-port)))
     (apply fprintf port f args)
     (flush-output-port port)))

    (display "writing to output file biophilia.c\n\r")
    (with-output-to-file "biophilia.c"
      (lambda ()
        (printf code)
        ))

code doesn't segfault anymore

but in the end of file: Error: ( : 25) not enough arguments



来源:https://stackoverflow.com/questions/10909278/how-to-write-alike-display-printf-to-file-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!