help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Efficiently checking the initial contents of a file


From: Juanma Barranquero
Subject: Re: Efficiently checking the initial contents of a file
Date: Fri, 16 May 2008 16:03:09 +0200

On Fri, May 16, 2008 at 2:52 PM, Nordlöw <address@hidden> wrote:

> (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)
>          ))))

A few additional comments:

 - BEG can be a regular expression, in which case the length of it can
be a red herring; for example (file-begin-p "[ABC]\\{20\\}") will
always return nil. Perhaps you could do

   (defun file-begin-p (filename beg &optional len)
      ...
     (let ((width (or len (string-width beg))))
       ...

so you can pass a length if needed.

 - If you don't want to pass a regexp, it is advisable to remember
using regexp-quote, otherwise (file-begin-p "A*") is always going to
return t.

 - Mixing `insert-file-contents-literally' and `string-width' does not
seem like a good idea. Better use `string-bytes', or, if BEG can
contain non-ASCII chars, use `insert-file-contents' and `length'. I'd
recommend that second route.

Hope this helps,

   Juanma

reply via email to

[Prev in Thread] Current Thread [Next in Thread]