2011-05-25 06:42:17 -04:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
2015-01-30 10:52:44 -05:00
|
|
|
#include <limits.h>
|
2011-05-25 06:42:17 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2011-05-25 15:40:47 -04:00
|
|
|
#include <string.h>
|
2011-05-25 06:42:17 -04:00
|
|
|
#include <unistd.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
|
|
|
|
head(FILE *fp, const char *str, long n)
|
|
|
|
{
|
|
|
|
char *buf = NULL;
|
|
|
|
size_t size = 0;
|
|
|
|
ssize_t len;
|
|
|
|
unsigned long i = 0;
|
|
|
|
|
|
|
|
while (i < n && ((len = getline(&buf, &size, fp)) != -1)) {
|
|
|
|
fputs(buf, stdout);
|
|
|
|
if (buf[len - 1] == '\n')
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
free(buf);
|
|
|
|
if (ferror(fp))
|
|
|
|
eprintf("%s: read error:", str);
|
|
|
|
}
|
2011-05-25 06:42:17 -04:00
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
static void
|
|
|
|
usage(void)
|
|
|
|
{
|
2015-01-25 16:01:26 -05:00
|
|
|
eprintf("usage: %s [-n lines] [-N] [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[])
|
|
|
|
{
|
|
|
|
long n = 10;
|
|
|
|
FILE *fp;
|
2014-11-20 17:39:29 -05:00
|
|
|
int ret = 0;
|
2014-11-20 17:51:18 -05:00
|
|
|
int newline, many;
|
2011-05-25 06:42:17 -04:00
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
ARGBEGIN {
|
|
|
|
case 'n':
|
2015-01-30 10:52:44 -05:00
|
|
|
n = estrtonum(EARGF(usage()), 0, LONG_MAX);
|
2013-06-14 14:20:47 -04:00
|
|
|
break;
|
2013-11-11 14:53:01 -05:00
|
|
|
ARGNUM:
|
|
|
|
n = ARGNUMF(0);
|
|
|
|
break;
|
2013-06-14 14:20:47 -04:00
|
|
|
default:
|
|
|
|
usage();
|
|
|
|
} ARGEND;
|
|
|
|
|
2014-11-13 12:29:30 -05:00
|
|
|
if (argc == 0) {
|
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;
|
|
|
|
for (newline = 0; argc > 0; argc--, argv++) {
|
2014-11-13 12:29:30 -05:00
|
|
|
if (!(fp = fopen(argv[0], "r"))) {
|
2014-04-22 06:43:01 -04:00
|
|
|
weprintf("fopen %s:", argv[0]);
|
2014-11-20 17:39:29 -05:00
|
|
|
ret = 1;
|
2014-04-22 06:43:01 -04:00
|
|
|
continue;
|
|
|
|
}
|
2014-11-20 17:51:18 -05:00
|
|
|
if (many)
|
|
|
|
printf("%s==> %s <==\n",
|
|
|
|
newline ? "\n" : "", argv[0]);
|
|
|
|
newline = 1;
|
2014-04-22 06:43:01 -04:00
|
|
|
head(fp, argv[0], n);
|
|
|
|
fclose(fp);
|
2013-11-12 05:44:37 -05:00
|
|
|
}
|
2011-05-25 06:42:17 -04:00
|
|
|
}
|
2014-11-20 17:39:29 -05:00
|
|
|
return ret;
|
2011-05-25 06:42:17 -04:00
|
|
|
}
|