From: Trastabuga
Subject: Reading and writing a string to a file: different results?
Date: 
Message-ID: <973518bf-b41d-4caa-b17d-96970399320e@c19g2000prf.googlegroups.com>
Maybe the answer is really obvious but I just can't see it!
Having two simple function which one writes a string to a file and
another one reads a string, should give the same string.

(defun file-to-string (path)
  (if (probe-file path)
      (with-open-file (in path)
        (let ((str (make-string (file-length in))))
          (read-sequence str in)
          str))))

(defun string-to-file (filename str)
  (ensure-directories-exist filename)
  (with-open-file (out filename
                       :direction :output
                       :if-exists :supersede)
    (with-standard-io-syntax
      (print str out))))

1) I write a string: (string-to-file "/tmp/test" "\"some test string
\"")
2) I read a string: (file-to-string "/tmp/test") and the result is \"\\
\"some test string\\\"\"
Where the extra slashes are coming from? I am using sbcl on Ubuntu.

Thank you!
Andrew
From: Ari Johnson
Subject: Re: Reading and writing a string to a file: different results?
Date: 
Message-ID: <m2r6d9edfw.fsf@hermes.theari.com>
Trastabuga <·········@gmail.com> writes:

> Maybe the answer is really obvious but I just can't see it!
> Having two simple function which one writes a string to a file and
> another one reads a string, should give the same string.
>
> (defun file-to-string (path)
>   (if (probe-file path)
>       (with-open-file (in path)
>         (let ((str (make-string (file-length in))))
>           (read-sequence str in)
>           str))))
>
> (defun string-to-file (filename str)
>   (ensure-directories-exist filename)
>   (with-open-file (out filename
>                        :direction :output
>                        :if-exists :supersede)
>     (with-standard-io-syntax
>       (print str out))))
>
> 1) I write a string: (string-to-file "/tmp/test" "\"some test string
> \"")
> 2) I read a string: (file-to-string "/tmp/test") and the result is \"\\
> \"some test string\\\"\"
> Where the extra slashes are coming from? I am using sbcl on Ubuntu.

Read-sequence and print are not complements of each other.  Your call
to print puts the following line into the file, verbatim:
"\"some test string\""

Read-sequence then reads in each character without interpretation, so
you get a string containing the above.  You may want to use
write-sequence to put the string into the file.