How do I persist and restore my defstruct's to a file?

clojure

Solution

Tom Crayford's answer is close, but use the "pr" function instead of "print". "pr" produces strings that can be read back in with "read".

(defn save-db [db filename]
  (spit 
   filename 
   (with-out-str (pr db))))

(defn load-db [filename] 
  (with-in-str (slurp filename)
    (read)))

Note that this will not work if *print-dup* is set to true. See ticket #176 Note also that when you read the database back in, the records will be ordinary maps, not struct maps. Struct maps cannot yet be serialized with pr/read.

Problem

I want to persist my data to a file and restore the data when I rerun the program. I've defined my defstruct as such: (defstruct bookmark :url :title :comments) Program will simply do the following: 1. Load the defstruct's from url-db.txt 2. Read from an import file(s) passed into *command-line-args* and add to internal data var. 3. Rewrite the url-db.txt file. Sample import file: www.cnn.com|News|This is CNN www.msnbc.com|Search| news.ycombinator.com|News|Tech News

Original source

Related problems