sbase/head.c

70 lines
1.1 KiB
C
Raw Normal View History

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