[plt-scheme] reading a whole file

From: Eli Barzilay (eli at barzilay.org)
Date: Mon Nov 10 03:42:09 EST 2008

On Nov 10, Shriram Krishnamurthi wrote:
> Fast on the heels of this thread, today I had to insert a bunch of
> JavaScript gobbledygook into each of my HTML files.  Here's the Scheme
> code I wrote:
> ----------
> (define tracker "... gobbledygook goes here ...
> ")
> (define (go f)
>   (let ([txt (with-input-from-file f
>                (lambda () (read-string (file-size f))))])
>     (let ([new-txt
>            (regexp-replace (regexp "</HEAD>")
>                            txt
>                            (string-append tracker "</HEAD>"))])
>       (if (string=? txt new-txt)
>           (printf "Pattern not found in ~a~n" f)
>           (with-output-to-file "out"
>             (lambda () (write-string new-txt)))))))
> (go (vector-ref (current-command-line-arguments) 0))
> ----------
> [Orthogonal note: writing the gobbledygook was itself a bit painful,
> and made me better appreciate Python's quoting.]

You mean arbitrary text?  Like

  some text here

Or even better:

  (define foo "FOO")

  #reader scribble/reader
    blah blah

And before you say how much more verbose this is, you can just put the
#reader line before the #lang line and then you just use the @ syntax
anywhere in the module.  (Perhaps it makes sense to add it to
scheme/base at some point in the future...)

> It sure would have been nice to make the above code both shorter and
> more robust with FILE->STRING and STRING->FILE...

The only question is how many functions to have in that interface.
Currently, I see 16 of them:

  file->strings ; list of strings, read with read-line
  file->bytess  ; bad name, and perhaps not needed anyway
  port->...     ; port versions of all of the above
  string->file  ; reverse direction

I hope that there's some way to cut all that down somehow...  (The
file/port cannot be done based on the input value if the two functions
come from scheme/port and scheme/file, some keyword argument that
makes it return bytes/string, or a list of lines seems ugly.)

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!

Posted on the users mailing list.