(spit f content & options)
Opposite of slurp. Opens f with writer, writes content, then closes f. Options passed to clojure.java.io/writer.
user=> (spit "flubber.txt" "test")
nil
user=> (slurp "flubber.txt")
"test"
user=> (spit "event.log" "test 1\
" :append true)
nil
user=> (spit "event.log" "test 2\
" :append true)
nil
user=> (println (slurp "event.log"))
test 1
test 2
nil
(defn append-to-file
"Uses spit to append to a file specified with its name as a string, or
anything else that writer can take as an argument. s is the string to
append."
[file-name s]
(spit file-name s :append true))
;;Create a record and save a log message to a log file
;;Constructor with side effects
;;define a Person record
(defrecord Person [fname lname])
;;define a function to save a log message into the log.txt using spit and :append
(defn log-entry [msg] (spit "log.txt" (apply str msg "\
") :append true))
;;build the constructor which: 1) log the message; 2)create a Person
(defn make-person [fname lname]
(log-entry (apply str "[log] New Person created : " lname "," fname))
(->Person fname lname))
;;create a person
(def person (make-person "John" "Smith"))
;;print the content of the log.txt to the console
(println (slurp "log.txt"))