我知道insert-file-contents
惯用语:
(defun read-lines (filePath)
(with-temp-buffer
(insert-file-contents filePath)
(split-string (buffer-string) "\n" t)))
但是,有一种更自然的方式来逐行读取文件而不一次读取整个文件吗?我正在寻找类似fopen
/ fread
的功能。
答案 0 :(得分:0)
我认为在emacs中处理文件的自然方法是将文件加载到缓冲区中,然后可以逐行处理它。还要看一下ergoemacs中的this answer in emacs stackexchange和this 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函数:
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)))