commit: 36767da66e4aa63bd7795f20ed7a907fb0207e13
parent d2128cb6baa49823f2929c34f8c3fc326bee2570
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Mon, 9 Sep 2024 03:18:23 +0200
cmd/head: add support for -z option
Diffstat:
3 files changed, 17 insertions(+), 7 deletions(-)
diff --git a/cmd/head.1 b/cmd/head.1
@@ -9,7 +9,7 @@
.Nd print first part of files
.Sh SYNOPSIS
.Nm
-.Op Fl qv
+.Op Fl qvz
.Op Fl c Ar size | Fl n Ar num | Fl Ar num
.Op Ar file...
.Sh DESCRIPTION
@@ -53,6 +53,8 @@ are given.
.It Fl v
Always print header, regardless of the number of given
.Ar file .
+.It Fl z
+Use NULL as line delimiter, not newline.
.El
.Pp
If no option is specified,
@@ -78,9 +80,10 @@ IEEE Std 1003.1-2024 (“POSIX.1”)
specification.
.br
The
-.Fl q
+.Fl q ,
+.Fl v ,
and
-.Fl v
+.Fl z
options are extensions.
The
.Fl Ar num
diff --git a/cmd/head.c b/cmd/head.c
@@ -27,6 +27,8 @@ size_t bytes = 0;
char *buf = NULL;
size_t buflen = 0;
+int delim = '\n';
+
static int
copy_bytes(const char *filename)
{
@@ -117,7 +119,7 @@ copy_lines(const char *filename)
for(size_t i = 0; i < lines; i++)
{
assert(errno == 0);
- ssize_t nread = getline(&buf, &buflen, in);
+ ssize_t nread = getdelim(&buf, &buflen, delim, in);
if(nread < 0)
{
if(errno == 0) break;
@@ -149,7 +151,7 @@ copy_lines(const char *filename)
static void
usage(void)
{
- fprintf(stderr, "Usage: head [-qv] [-c size | -n num | -num] [file...]\n");
+ fprintf(stderr, "Usage: head [-qvz] [-c size | -n num | -num] [file...]\n");
}
int
@@ -183,7 +185,7 @@ main(int argc, char *argv[])
continue;
}
- int c = getopt(argc, argv, ":qvc:n:");
+ int c = getopt(argc, argv, ":qvc:n:z");
if(c == -1) break;
switch(c)
@@ -226,6 +228,9 @@ main(int argc, char *argv[])
}
break;
}
+ case 'z':
+ delim = '\0';
+ break;
case ':':
fprintf(stderr, "head: Error: Missing operand for option: '-%c'\n", optopt);
usage();
diff --git a/test-cmd/head.sh b/test-cmd/head.sh
@@ -4,7 +4,7 @@
WD="$(dirname "$0")/../"
target="${WD}/cmd/head"
-plans=11
+plans=12
. "${WD}/test-cmd/tap.sh"
t --input="$(seq 1 20)" 20l '' "$(seq 1 10)
@@ -35,3 +35,5 @@ t --input="$(seq 1 2)" opt_q "-q - ${WD}/test-cmd/inputs/empty" '1
t --input='' opt_v '-v -' '==> - <==
'
+
+t z3 "-n 3 -z ${WD}/test-cmd/inputs/strings/length" "$(printf '1\0_2\0__3\0')"