implementation of file-map

Started by John_Small, June 08, 2007, 05:34:07 PM

Previous topic - Next topic

John_Small

This was done in a hurry and briefly tested.



It allows you to map the lines from the input to

the output file.  The optional 4th argument

indicates the out-file is temporary and that the output

file replaces the input file when finished.  If the function

succeeds it returns the final file name otherwise it returns

nil.  I didn't look to see if newLISP has a temp file

name generator so the function prototype could

be changed to something more appropriate.

I'm using newLISP to write file stream combinators

and filters so I'll be using this all the time.  Seems

like it would be easy to include something similar

in functionality with the standard library.  The reason

I didn't use read-file and write-file is because

the files I'm filtering are gigantic and can't fit into

memory.







(define (file-map fn-line-map filename out-filename out-temp)

  (setq out-file (open out-filename "write"))

  (if out-file

    (begin

      (setq in-file (open filename "read"))

      (setq out-written nil)

      (if in-file

        (begin

          (while (read-line in-file)

            (write-line (fn-line-map (current-line)) out-file))

          (setq out-written true)

          (close in-file)

        )

      )

      (close out-file)

      (if out-written

        (if out-temp

          (begin

            (delete-file filename)

            (rename-file out-filename filename)

            filename

          )

          out-filename

        )

        nil

      )

    )

    nil

  )

)




John_Small

#1
I delete the output file if I fail to write anything.



(define (file-map fn-line-map filename out-filename out-temp)

  (setq out-file (open out-filename "write"))

  (if out-file

    (begin

      (setq in-file (open filename "read"))

      (setq out-written nil)

      (if in-file

        (begin

          (while (read-line in-file)

            (write-line (fn-line-map (current-line)) out-file))

          (setq out-written true)

          (close in-file)

        )

      )

      (close out-file)

      (if out-written

        (if out-temp

          (begin

            (delete-file filename)

            (rename-file out-filename filename)

            filename

          )

          out-filename

        )

        (begin

          (delete-file out-filename) ;; since nothing was written

          nil

        )

      )

    )

    nil

  )

)