Move the code to detect non-regular files to the point where the
file is being opened.  The line-counting code in m_status_print
now only has to handle regular files.

Still check the error return from the open call in m_status_print.
This permits detection of the case where a file becomes unreadable
between it first being opened and the call to m_status_print.  But
mark the file as being non-regular so we don't try that again.

function                                             old     new   delta
reinitialize                                         197     245     +48
m_status_print                                       409     379     -30
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 48/-30)             Total: 18 bytes

Signed-off-by: Ron Yorston <[email protected]>
---
 miscutils/less.c | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/miscutils/less.c b/miscutils/less.c
index dd932c5..6a59a00 100644
--- a/miscutils/less.c
+++ b/miscutils/less.c
@@ -167,7 +167,8 @@ enum { pattern_valid = 0 };
 
 enum {
        READING_FILE = -1,
-       READING_STDIN = -2
+       READING_STDIN = -2,
+       READING_NONREG = -3
 };
 
 struct globals {
@@ -633,15 +634,15 @@ static void m_status_print(void)
                int count, fd;
                ssize_t len, i;
                char buf[4096];
-               struct stat stbuf;
 
-               /* count number of lines in file */
+               /* count number of lines in (regular) file */
                count = 0;
                fd = open(filename, O_RDONLY);
-               if (fd < 0)
+               if (fd < 0) {
+                       /* somebody stole my file! */
+                       num_lines = READING_NONREG;
                        goto skip;
-               if (fstat(fd, &stbuf) != 0 || !S_ISREG(stbuf.st_mode))
-                       goto do_close;
+               }
                while ((len = safe_read(fd, buf, sizeof(buf))) > 0) {
                        for (i = 0; i < len; ++i) {
                                if (buf[i] == '\n' && ++count == MAXLINES)
@@ -650,7 +651,6 @@ static void m_status_print(void)
                }
  done:
                num_lines = count;
- do_close:
                close(fd);
  skip: ;
        }
@@ -939,6 +939,13 @@ static void buffer_line(int linenum)
 static void open_file_and_read_lines(void)
 {
        if (filename) {
+#if ENABLE_FEATURE_LESS_FLAGS
+               struct stat stbuf;
+
+               xstat(filename, &stbuf);
+               if (!S_ISREG(stbuf.st_mode))
+                       num_lines = READING_NONREG;
+#endif
                xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
        } else {
                /* "less" with no arguments in argv[] */
-- 
2.4.3

_______________________________________________
busybox mailing list
[email protected]
http://lists.busybox.net/mailman/listinfo/busybox

Reply via email to