2011-05-25 06:42:17 -04:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
|
|
|
#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-06-01 09:04:32 -04:00
|
|
|
#include "text.h"
|
2011-05-25 06:42:17 -04:00
|
|
|
#include "util.h"
|
|
|
|
|
|
|
|
static void head(FILE *, const char *, long);
|
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
static void
|
|
|
|
usage(void)
|
|
|
|
{
|
|
|
|
eprintf("usage: %s [-n] [FILE...]\n", argv0);
|
|
|
|
}
|
|
|
|
|
2011-05-25 06:42:17 -04:00
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
long n = 10;
|
|
|
|
FILE *fp;
|
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
ARGBEGIN {
|
|
|
|
case 'n':
|
|
|
|
n = estrtol(EARGF(usage()), 0);
|
|
|
|
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;
|
|
|
|
|
|
|
|
if(argc == 0) {
|
2011-05-25 06:42:17 -04:00
|
|
|
head(stdin, "<stdin>", n);
|
2014-04-22 06:43:01 -04:00
|
|
|
} else {
|
|
|
|
for(; argc > 0; argc--, argv++) {
|
|
|
|
if(!(fp = fopen(argv[0], "r"))) {
|
|
|
|
weprintf("fopen %s:", argv[0]);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
head(fp, argv[0], n);
|
|
|
|
fclose(fp);
|
2013-11-12 05:44:37 -05:00
|
|
|
}
|
2011-05-25 06:42:17 -04:00
|
|
|
}
|
2013-06-14 14:20:47 -04:00
|
|
|
|
2014-10-02 18:46:04 -04:00
|
|
|
return 0;
|
2011-05-25 06:42:17 -04:00
|
|
|
}
|
|
|
|
|
2014-06-01 08:59:47 -04:00
|
|
|
static void
|
2011-05-25 06:42:17 -04:00
|
|
|
head(FILE *fp, const char *str, long n)
|
|
|
|
{
|
2014-06-01 09:04:32 -04:00
|
|
|
char *buf = NULL;
|
|
|
|
size_t size = 0;
|
|
|
|
ssize_t len;
|
|
|
|
unsigned long i = 0;
|
2011-05-25 06:42:17 -04:00
|
|
|
|
2014-06-01 09:04:32 -04:00
|
|
|
while(i < n && ((len = agetline(&buf, &size, fp)) != -1)) {
|
2011-05-25 06:42:17 -04:00
|
|
|
fputs(buf, stdout);
|
2014-06-01 09:04:32 -04:00
|
|
|
if(buf[len - 1] == '\n')
|
2011-05-25 15:40:47 -04:00
|
|
|
i++;
|
|
|
|
}
|
2014-06-01 09:04:32 -04:00
|
|
|
free(buf);
|
2011-05-25 06:42:17 -04:00
|
|
|
if(ferror(fp))
|
|
|
|
eprintf("%s: read error:", str);
|
|
|
|
}
|