From ce630dfc7ef32ff7e35c627bd061a45ce9053d9d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?P=C3=A1draig=20Brady?= <P@draigBrady.com>
Date: Sun, 5 Feb 2023 19:52:31 +0000
Subject: [PATCH] wc: ensure we update file offset

* src/wc.c (wc): Update the offset when not reading,
and do read if we can't update the offset.
* tests/misc/wc-proc.sh: Add a test case.
* NEWS: Mention the bug fix.
Fixes https://bugs.gnu.org/61300

Conflict:NEWS and tests/misc/wc-proc.sh context adaption
Reference:https://github.com/coreutils/coreutils/commit/ce630dfc7ef32ff7e35c627bd061a45ce9053d9d

---
 NEWS                  |  4 ++++
 src/wc.c              |  5 ++++-
 tests/misc/wc-proc.sh | 12 ++++++++++++
 3 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/NEWS b/NEWS
index 5320b9c..ce6e2b7 100644
--- a/NEWS
+++ b/NEWS
@@ -3,6 +3,10 @@ GNU coreutils NEWS                                    -*- outline -*-
 * Noteworthy changes in release 9.0 (2021-09-24) [stable]

 ** Bug fixes
+  `wc -c` will again correctly update the read offset of inputs.
+  Previously it deduced the size of inputs while leaving the offset unchanged.
+  [bug introduced in coreutils-8.27]
+
   'pr --length=1 --double-space' no longer enters an infinite loop.
   [This bug was present in "the beginning".]

diff --git a/src/wc.c b/src/wc.c
index 801396a15..becceda98 100644
--- a/src/wc.c
+++ b/src/wc.c
@@ -450,7 +450,10 @@ wc (int fd, char const *file_x, struct fstatus *fstatus, off_t current_pos)
                  beyond the end of the file.  As in the example above.  */
 
               bytes = end_pos < current_pos ? 0 : end_pos - current_pos;
-              skip_read = true;
+              if (bytes && 0 <= lseek (fd, bytes, SEEK_CUR))
+                skip_read = true;
+              else
+                bytes = 0;
             }
           else
             {
diff --git a/tests/misc/wc-proc.sh b/tests/misc/wc-proc.sh
index 5eb43b982..2307f2c38 100755
--- a/tests/misc/wc-proc.sh
+++ b/tests/misc/wc-proc.sh
@@ -42,4 +42,16 @@ cat <<\EOF > exp
 EOF
 compare exp out || fail=1
 
+# Ensure we update the offset even when not reading,
+# which wasn't the case from coreutils-8.27 to coreutils-9.2
+{ wc -c; wc -c; } < no_read >  out || fail=1
+{ wc -c; wc -c; } < do_read >> out || fail=1
+cat <<\EOF > exp
+2
+0
+1048576
+0
+EOF
+compare exp out || fail=1
+
 Exit $fail
-- 
2.36.1

