[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Efficiently checking the initial contents of a file
From: |
Nordlöw |
Subject: |
Re: Efficiently checking the initial contents of a file |
Date: |
Fri, 16 May 2008 05:52:40 -0700 (PDT) |
User-agent: |
G2/1.0 |
On 16 Maj, 13:12, David Hansen <david.han...@gmx.net> wrote:
> On Fri, 16 May 2008 03:16:13 -0700 (PDT) Nordlöw wrote:
>
> > How can I efficiently using pure emacs-lisp (without calling any
> > external process) investigate the first bytes of a file?
>
> > My guess is
> > - Open parts of the file into a buffer or string.
> > - Alt 1. Switch to the buffer and do things.
>
> (with-temp-buffer
> ;; Read the first 42 characters (not bytes) into the temp buffer.
> (insert-file-contents filename nil 0 42)
> ;; Do whatever you want to do here.
> )
>
> David
Great!
Thanks for all the help!
I wanted a quick way of discarding ELFs from my tags-query-replace()
operations.
This is the result of my coding.
Is it ok to use string-width() and looking-at() if don't care about
different string encodings, that is I just want to compare binary byte-
arrays?
;; For additional speed you can use
;; `insert-file-contents-literally', if you don't need code
;; conversions, decompression, etc.
(defun file-begin-p (filename beg)
"Determine if FILENAME begins with BEG."
(interactive "fFile to investigate: ")
(if (and (file-exists-p filename)
(file-readable-p filename))
(with-temp-buffer
(let ((width (string-width beg)))
(insert-file-contents-literally filename nil 0 width)
(looking-at beg)
))))
;; TEST: (file-begin-p "/bin/ls" "ELF")
(defun file-begin-ELF-p (filename)
"Return non-nil if FILENAME is an ELF (Executable and Linkable
Format)"
(interactive "fFile to investigate: ")
(file-begin-p filename "ELF")
)
;; TEST: (file-begin-ELF-p "/bin/ls")
Thanks again,
Nordlöw