6

I'm wondering if there's a terse (i.e. single function) approach for reading a file's content given its path and returning it as a string.

My go-to has been:

(with-temp-buffer
  (insert-file-contents some-path)
  (buffer-string))
  => "it's a short file"

but a helper function defined per project or this two-functions-and-a-macro copy-pasta seem unnecessary. Is there a utility function or common pattern I'm missing?

Judging from the existence of gntp-file-string, ffap-file-exists-string, org-file-contents, and a few others I'm guessing there is not.

Drew
  • 75,699
  • 9
  • 109
  • 225
ebpa
  • 7,319
  • 26
  • 53

1 Answers1

6

There is not. You can report-emacs-bug and suggest that one be included.

One reason I can think of for not including such a function is that there are different reasonable ways to handle errors. E.g. if the file is not readable, what should the function do? Return nil? Return empty string ("")? Signal an error?

Update: f-read-text in f.el does what you want.

Tianxiang Xiong
  • 3,848
  • 16
  • 27
  • And for that reason I can understand it not being in elisp itself. It would probably be a good addition to `f.el`. `org-file-contents` seems like a reasonable implementation (it includes a *noerror* parameter), but as you say there are subtle variations of behavior one might desire. Per POLA, however; I would consider `""` to indicate an empty (zero-length) file. – ebpa Mar 29 '17 at 05:20
  • 2
    [`f-read-text`](https://github.com/rejeep/f.el/blob/v0.19.0/f.el#L209) in `f.el` does what you want. – Tianxiang Xiong Mar 29 '17 at 05:23
  • Grrr. and I knew about f-read-bytes. I'm not sure how I missed that. The global symbol table needs a synonym table! :-P – ebpa Mar 29 '17 at 05:30
  • 1
    Another subtlety is whether to use `insert-file-contents` or `insert-file-contents-literally`. Often you'll want to use the latter, but it not dealing with encodings sucks. – wasamasa Mar 29 '17 at 06:18
  • 1
    "if _condition x_, what should the function do" can be asked for almost any function. So, I doubt this has anything to do with it. – politza Mar 29 '17 at 15:50