sbase/head.c

57 lines
908 B
C
Raw Normal View History

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>
#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;
default:
usage();
} ARGEND;
if(argc == 0) {
2011-05-25 06:42:17 -04:00
head(stdin, "<stdin>", n);
2013-06-14 14:20:47 -04:00
} else for(; argc > 0; argc--, argv++) {
if(!(fp = fopen(argv[0], "r")))
eprintf("fopen %s:", argv[0]);
head(fp, argv[0], n);
2011-05-25 06:42:17 -04:00
fclose(fp);
}
2013-06-14 14:20:47 -04:00
return EXIT_SUCCESS;
2011-05-25 06:42:17 -04:00
}
void
head(FILE *fp, const char *str, long n)
{
char buf[BUFSIZ];
2011-05-25 15:40:47 -04:00
long i = 0;
2011-05-25 06:42:17 -04:00
2011-05-25 15:40:47 -04:00
while(i < n && fgets(buf, sizeof buf, fp)) {
2011-05-25 06:42:17 -04:00
fputs(buf, stdout);
2011-05-25 15:40:47 -04:00
if(buf[strlen(buf)-1] == '\n')
i++;
}
2011-05-25 06:42:17 -04:00
if(ferror(fp))
eprintf("%s: read error:", str);
}
2013-06-14 14:20:47 -04:00