From ec73fe07a9f9a66f8d0b0835a542e581de423632 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Wed, 23 Jul 2025 17:38:32 -0700 Subject: [PATCH] Simplify file end finding in insert-file-contents MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * src/fileio.c (Finsert_file_contents): Don’t give up finding the file’s end merely because SEEK_END fails. Try a small test read anyway. This might work in non-POSIX file systems where SEEK_END is not allowed, and trying is easy and simplifies the code. (cherry picked from commit 4c791549496d1edbed7ba792994381e6cdc01184) --- src/fileio.c | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/src/fileio.c b/src/fileio.c index ead833a6ac0..c042089ac85 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -4525,27 +4525,26 @@ by calling `format-decode', which see. */) if (endpos == TYPE_MAXIMUM (off_t)) { endpos = emacs_fd_lseek (fd, 0, SEEK_END); - giveup_match_end = endpos < 0; - if (!giveup_match_end) - { - /* Check that read reports EOF soon, to catch platforms - where SEEK_END can report wildly small offsets. */ - ptrdiff_t n = emacs_full_read (fd, read_buf, sizeof read_buf); - if (n < 0) - report_file_error ("Read error", orig_filename); - curpos = endpos += n; + if (endpos < 0) + endpos = curpos; - /* Give up if the file grew more than even the test read. */ - giveup_match_end = n == sizeof read_buf; + /* Check that read reports EOF soon, to catch platforms + where SEEK_END fails or reports too-small offsets. */ + ptrdiff_t n = emacs_full_read (fd, read_buf, sizeof read_buf); + if (n < 0) + report_file_error ("Read error", orig_filename); + curpos = endpos += n; - if (!giveup_match_end) - { - /* Shrink the file's head if the file shrank to - be smaller than its head. */ - off_t offset_from_beg = endpos - beg_offset; - if (offset_from_beg < same_at_start - BEGV_BYTE) - same_at_start = max (0, offset_from_beg) + BEGV_BYTE; - } + /* Give up if the file extends past the test read. */ + giveup_match_end = n == sizeof read_buf; + + if (!giveup_match_end) + { + /* Shrink the file's head if the file shrank to + be smaller than its head. */ + off_t offset_from_beg = endpos - beg_offset; + if (offset_from_beg < same_at_start - BEGV_BYTE) + same_at_start = max (0, offset_from_beg) + BEGV_BYTE; } } } -- 2.39.5