2010-09-03

elisp: read file content in one shot

Here's a short elisp example to get file content into a string.

;; thanks to “Pascal J Bourguignon” and “TheFlyingDutchman <zzbba...@aol.com>”. 2010-09-02
(defun get-string-from-file (filePath)
  "Return FILEPATH's file content."
  (with-temp-buffer
    (insert-file-contents filePath)
    (buffer-string)))

And, remember, you can also get them into list of lines.

(defun read-lines (filePath) 
  "Return a list of lines of a file at FILEPATH." 
  (with-temp-buffer 
    (insert-file-contents filePath) 
    (split-string (buffer-string) "\n" t)))

For more about processing a file line by line, see: Process a File Line by Line in Emacs Lisp.