2011-05-25 06:42:17 -04:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
2015-01-31 19:24:03 -05:00
|
|
|
#include <stdint.h>
|
2011-05-25 06:42:17 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2014-11-13 12:29:30 -05:00
|
|
|
|
2011-05-25 06:42:17 -04:00
|
|
|
#include "util.h"
|
|
|
|
|
2015-01-25 16:01:26 -05:00
|
|
|
static void
|
2015-03-04 18:58:12 -05:00
|
|
|
head(FILE *fp, const char *fname, size_t n)
|
2015-01-25 16:01:26 -05:00
|
|
|
{
|
|
|
|
char *buf = NULL;
|
2015-03-04 18:58:12 -05:00
|
|
|
size_t i = 0, size = 0;
|
2015-01-25 16:01:26 -05:00
|
|
|
ssize_t len;
|
|
|
|
|
2015-03-27 09:49:48 -04:00
|
|
|
while (i < n && (len = getline(&buf, &size, fp)) > 0) {
|
2015-01-25 16:01:26 -05:00
|
|
|
fputs(buf, stdout);
|
2015-03-04 18:58:12 -05:00
|
|
|
i += (len && (buf[len - 1] == '\n'));
|
2015-01-25 16:01:26 -05:00
|
|
|
}
|
|
|
|
free(buf);
|
|
|
|
if (ferror(fp))
|
2015-03-04 18:58:12 -05:00
|
|
|
eprintf("getline %s:", fname);
|
2015-01-25 16:01:26 -05:00
|
|
|
}
|
2011-05-25 06:42:17 -04:00
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
static void
|
|
|
|
usage(void)
|
|
|
|
{
|
2015-03-05 03:10:00 -05:00
|
|
|
eprintf("usage: %s [-num | -n num] [file ...]\n", argv0);
|
2013-06-14 14:20:47 -04:00
|
|
|
}
|
|
|
|
|
2011-05-25 06:42:17 -04:00
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
2015-01-31 19:24:03 -05:00
|
|
|
size_t n = 10;
|
2011-05-25 06:42:17 -04:00
|
|
|
FILE *fp;
|
2015-03-04 18:58:12 -05:00
|
|
|
int ret = 0, newline, many;
|
2011-05-25 06:42:17 -04:00
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
ARGBEGIN {
|
|
|
|
case 'n':
|
2015-01-31 19:24:03 -05:00
|
|
|
n = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
|
2013-06-14 14:20:47 -04:00
|
|
|
break;
|
2013-11-11 14:53:01 -05:00
|
|
|
ARGNUM:
|
2015-01-30 11:45:44 -05:00
|
|
|
n = ARGNUMF();
|
2013-11-11 14:53:01 -05:00
|
|
|
break;
|
2013-06-14 14:20:47 -04:00
|
|
|
default:
|
|
|
|
usage();
|
|
|
|
} ARGEND;
|
|
|
|
|
2015-03-04 18:58:12 -05:00
|
|
|
if (!argc) {
|
2011-05-25 06:42:17 -04:00
|
|
|
head(stdin, "<stdin>", n);
|
2014-04-22 06:43:01 -04:00
|
|
|
} else {
|
2014-11-20 17:51:18 -05:00
|
|
|
many = argc > 1;
|
2015-03-04 18:58:12 -05:00
|
|
|
for (newline = 0; *argv; argc--, argv++) {
|
|
|
|
if (!(fp = fopen(*argv, "r"))) {
|
|
|
|
weprintf("fopen %s:", *argv);
|
2014-11-20 17:39:29 -05:00
|
|
|
ret = 1;
|
2014-04-22 06:43:01 -04:00
|
|
|
continue;
|
|
|
|
}
|
2015-03-05 18:32:22 -05:00
|
|
|
if (many) {
|
|
|
|
if (newline)
|
|
|
|
putchar('\n');
|
2015-03-04 18:58:12 -05:00
|
|
|
printf("==> %s <==\n", *argv);
|
2015-03-05 18:32:22 -05:00
|
|
|
}
|
2014-11-20 17:51:18 -05:00
|
|
|
newline = 1;
|
2015-03-04 18:58:12 -05:00
|
|
|
head(fp, *argv, n);
|
2014-04-22 06:43:01 -04:00
|
|
|
fclose(fp);
|
2013-11-12 05:44:37 -05:00
|
|
|
}
|
2011-05-25 06:42:17 -04:00
|
|
|
}
|
2015-03-04 18:58:12 -05:00
|
|
|
|
2014-11-20 17:39:29 -05:00
|
|
|
return ret;
|
2011-05-25 06:42:17 -04:00
|
|
|
}
|