【问题标题】:Is there a fopen-like function in elispelisp 中是否有类似 fopen 的功能
【发布时间】:2018-10-14 13:11:33
【问题描述】:

我知道insert-file-contents成语:

(defun read-lines (filePath)
  (with-temp-buffer
    (insert-file-contents filePath)
    (split-string (buffer-string) "\n" t)))

但是有没有更自然的方法来逐行读取文件而不是一次读取整个文件?我正在寻找类似fopen/fread 的功能。

【问题讨论】:

  • 我要注意的是,您可以将 BEG 和 END 参数传递给 insert-file-contents 以仅插入文件的一部分。不是您要的,但值得指出。

标签: file emacs


【解决方案1】:

我认为在 emacs 中处理文件的自然方式是将文件加载到缓冲区中,然后您可以逐行处理它。也可以看看来自 ergoemacs 的 this answer in emacs stackexchangethis blog post

例如:

ELISP> (find-file "foo.txt")
#<buffer foo.txt>
ELISP> (goto-char 1)
1 (#o1, #x1, ?\C-a)
ELISP> (while (not (eobp))
  (print (current-line-contents))
  (forward-line 1))

为了不获取属性,可以使用函数thing-at point:

ELISP> (goto-char 1)
1 (#o1, #x1, ?\C-a)
ELISP> (while (not (eobp))
         (print (thing-at-point 'line t))
         (forward-line 1))

"line 1
"

"line 2
"

"line 3
"

"line 4
"

nil

如果您需要为speed reasons try 使用临时缓冲区:

 (with-temp-buffer
         (insert-file-contents "./foo.txt")
         (while (not (eobp))
           (print (thing-at-point 'line t))
           (forward-line 1)))

【讨论】:

  • 我将文件复制到缓冲区的问题是速度非常慢。非缩小的 JSON 文件可能需要五分钟。特别是当文件是二进制文件或不包含行尾时,速度很慢。
  • 我更新了这个问题,也许它对你有用,现在就速度而言
猜你喜欢
  • 2012-08-01
  • 2023-04-07
  • 1970-01-01
  • 2021-11-14
  • 2015-11-21
  • 2019-12-19
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多