~sircmpwn/ctools

This thread contains a patchset. You're looking at the original emails, but you may wish to use the patch review UI. Review patch
1

[PATCH] Implement head

Nicolai Dagestad
Details
Message ID
<20190911165942.344009-1-nicolai@dagestad.fr>
DKIM signature
pass
Download raw message
Patch: +92 -0
---
 meson.build |  1 +
 src/head.c  | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 92 insertions(+)
 create mode 100644 src/head.c

diff --git a/meson.build b/meson.build
index 47b985b..ebe1c3c 100644
--- a/meson.build
+++ b/meson.build
@@ -20,6 +20,7 @@ oneshots = [
	'cmp',
	'comm',
	'false',
	'head',
	'logname',
	'nice', # Included in base but only effective under XSI
	'true',
diff --git a/src/head.c b/src/head.c
new file mode 100644
index 0000000..8c02e31
--- /dev/null
+++ b/src/head.c
@@ -0,0 +1,91 @@
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>

static void
usage(void)
{
	fprintf(stderr, "usage: head [−n number] [file...]\n");
}


static int
head(const char *path, int length, bool header, bool newline)
{
	FILE* file;
	if (path[0] == '-' && path[1] == '\0') {
		file = stdin;
	} else {
		if ((file = fopen(path, "r")) == NULL) {
			perror(path);
			return 1;
		}
	}

	ssize_t n;
	size_t buf_size=BUFSIZ;
	int curr_line=0;
	char *buf = calloc(sizeof(char), buf_size);
	printf("%s==> %s <==\n", newline? "\n" : "", path);
	while ((n=getline(&buf, &buf_size, file)) > 0) {
		ssize_t offs = 0;
		while (offs < n) {
			ssize_t o = printf("%s", buf);
			if (o < 0) {
				perror("write");
				fclose(file);
				return 1;
			}
			offs += o;
		}
		curr_line++;
		if ( curr_line >= length ){
			break;
		}
	}

	fclose(file);
	return 0;
}

int
main(int argc, char* argv[])
{
	int length=10;
	bool show_header=false;
	char opt;
	while ((opt = getopt(argc, argv, "n:")) != -1) {
		switch(opt) {
		case 'n': {
			char* endptr;
			length = strtol(optarg, &endptr, 10);
			printf("%s\n", optarg);
			if ( endptr != optarg+strlen(optarg) ){
				fprintf(stderr, "head: invalid number of lines: '%s'\n", optarg);
				return 1;
			}
			break;
		}
		default:
			usage();
			return 1;
		}
	}

	if ( argc < 2 ) {
		usage();
		return 1;
	}

	show_header = (optind - argc) > 1;
	for (int i=optind; i<argc; ++i){
		if ( head(argv[i], length, show_header, i!=optind) > 0 ){
			return 1;
		}
	}
	return 0;
}
-- 
2.23.0
Details
Message ID
<BWXCB1OKSHXA.33KUQ4ELUFV96@homura>
In-Reply-To
<20190911165942.344009-1-nicolai@dagestad.fr> (view parent)
DKIM signature
pass
Download raw message
This has severe style issues, please consult STYLE and the other
programs for reference and send a new patch. Additionally, a test script
and a man page will be required to merge this, along with an update to
the STATUS file.