Output into a file from another file

Discussion of Common Lisp
Post Reply
Indecipherable
Posts: 47
Joined: Fri Jun 03, 2011 5:30 am
Location: Behind you.
Contact:

Output into a file from another file

Post by Indecipherable » Tue Jun 21, 2011 10:31 am

I ran into a problem. I am trying to output the contents of file A (one on a line) into file B, so that it outputs as an AIML category.
I have this messed up code :D :

Code: Select all

(defun write-to-file (name content &optional c)
  (with-open-file (stream  name :external-format charset:iso-8859-1
                           :direction :io
                           :if-exists :overwrite
                           :if-does-not-exist :create )
  (format stream content)) name)
(defun aiml-printer (filename)
	(setf cat 
		(concatenate 'string
							"<category>" '(#\Newline) "<pattern>MOF ~s</pattern>" '(#\Newline) 
							"<template>" '(#\Newline #\Newline) "</template>" '(#\Newline) "</category>"))

	(loop for line = (read-line filename nil :eof)
		until (eq line :eof) do 
		(write-to-file "test.txt" cat line)))
So, for example, if file A contains:
A
B
C
D
on each line, the output in file B will be:

Code: Select all

<category>
<pattern>A</pattern>
<template>

</template>
</category>

<category>
<pattern>B</pattern>
<template>

</template>
</category>

<category>
<pattern>C</pattern>
<template>

</template>
</category>

<category>
<pattern>D</pattern>
<template>

</template>
</category>
Any Ideas?
T.I.A
Don't take the FUN out of DEFUN !

marcoxa
Posts: 85
Joined: Thu Aug 14, 2008 6:31 pm

Re: Output into a file from another file

Post by marcoxa » Tue Jun 21, 2011 12:20 pm

This is better. For something more sophisticated (shameless plug) look at http://within-parens.blogspot.com/2011/ ... -xhtm.html

Code: Select all

(defun write-to-file (out content cline)
  (format out content cline))

(defun aiml-printer (in-filename &optional (out-filename "test.aiml"))
  (let ((cat
         (formatter "<category>~%<pattern>MDF ~A</pattern>~@
                     <template>~2%</template>~%</category>"
                    ))
        )
    (with-open-file (in in-filename
                        :direction :input)
      (with-open-file (out out-filename
                           ;; :external-format charset:iso-8859-1 ; Not portale!!!!!
                           :direction :output
                           :if-exists :supersede
                           :if-does-not-exist :create)
        (loop for line = (read-line filename nil :eof)
              until (eq line :eof)
              do (write-to-file out cat line)))
      )))
Cheers
Marco Antoniotti

Indecipherable
Posts: 47
Joined: Fri Jun 03, 2011 5:30 am
Location: Behind you.
Contact:

Re: Output into a file from another file

Post by Indecipherable » Fri Jul 01, 2011 5:27 am

Thanks
Don't take the FUN out of DEFUN !

Post Reply