sbase/head.c

75 lines
1.2 KiB
C
Raw Normal View History

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