Make head lseek backwards to return unused data from seekable inputs.

This commit is contained in:
Rob Landley 2023-02-02 21:19:48 -06:00
parent e95bb78591
commit f0b4f9e5bb
2 changed files with 7 additions and 2 deletions

View File

@ -32,3 +32,5 @@ testcmd "-c 3" "-c 3" "one" "" "one\ntwo"
testcmd "-c bigger than input" "-c 3" "a" "" "a"
testcmd "-c 3 -n 1" "-c 3 -n 1" "one\n" "" "one\ntwo"
testcmd "-n 1 -c 3" "-n 1 -c 3" "one" "" "one\ntwo"
testing "unget" 'while read i; do echo =$i; head -n 1; done < input' \
'=one\ntwo\n=three\nfour\n=five\n' 'one\ntwo\nthree\nfour\nfive\n' ''

View File

@ -34,7 +34,7 @@ GLOBALS(
static void do_head(int fd, char *name)
{
long i, len, lines=TT.n, bytes=TT.c;
long i = 0, len = 0, lines = TT.n, bytes = TT.c;
if ((toys.optc > 1 && !FLAG(q)) || FLAG(v)) {
// Print an extra newline for all but the first file
@ -50,11 +50,14 @@ static void do_head(int fd, char *name)
if (bytes) {
i = bytes >= len ? len : bytes;
bytes -= i;
} else for(i=0; i<len;) if (toybuf[i++] == '\n' && !--lines) break;
} else for(i = 0; i<len;) if (toybuf[i++] == '\n' && !--lines) break;
xwrite(1, toybuf, i);
}
// attempt to unget extra data
if (len>i) lseek(fd, i-len, SEEK_CUR);
TT.file_no++;
}