hbin
hbin

Reputation: 2737

How to create an empty file by elisp?

I set an explicit file to customization created via the UI. It's named custom.el. Currently, I use the followed snippets to create this file if not exist.

(defconst custom-file (expand-file-name "custom.el" user-emacs-directory))
(unless (file-exists-p custom-file)
  (shell-command (concat "touch " custom-file)))

There is an ugly shell-command touch in, any other elisp functions can do this?

Upvotes: 16

Views: 5666

Answers (4)

nitin
nitin

Reputation: 71

(make-empty-file custom-file)

Check help to know more about it: C-h f make-empty-file

Upvotes: 2

Charl Botha
Charl Botha

Reputation: 4648

Perhaps a simpler solution to the underlying problem would be:

(defconst custom-file (expand-file-name "custom.el" user-emacs-directory))
;; NOERROR to ignore nonexistent file - Emacs will create it
(load custom-file t)

In other words, instead of manually creating custom.el, simply don't error when you try to load it (optional arg NOERROR is only for file existence error). Emacs will create the file the first time it writes out custom variables.

This is what I'm currently using in my init.el

Upvotes: 3

wagnermarques
wagnermarques

Reputation: 140

I write this function below based on Joao Tavara anwser in this post: How do I create an empty file in emacs?

(defun fzl-create-empty-file-if-no-exists(filePath)
   "Create a file with FILEPATH parameter."
   (if (file-exists-p filePath)
       (message (concat  "File " (concat filePath " already exists")))
     (with-temp-buffer (write-file filePath))))

Upvotes: 0

mathk
mathk

Reputation: 8133

You can use (write-region "" nil custom-file) not sure that is the ideal solution.

Upvotes: 24

Related Questions