File IO in Elisp

Elisp is tightly integrated with Emacs. Still, it is a complete programming language suitable for all types of programming jobs. If you are an Emacs user, you might have already used Elisp functions that manipulate text in a buffer. Elisp can also be used to write directly to disk files in the background (i.e, without actually displaying the associated buffer). The following code snippet creates a buffer, associates it with a file called “data” and writes a string to that buffer. Then the buffer is written back to the disk file.

(setq buffer (find-file-noselect "data"))

(save-current-buffer
  (set-buffer (get-buffer-create buffer))
  (insert "hello, world")
  (save-buffer))

The save-current-buffer function makes saves the current buffer and executes its body like progn. In the body of save-current-buffer we set the current buffer to our new “data” buffer, updates and writes it to disk. When the evaluation of save-current-buffer is finished, the original buffer is restored.