sbase/head.c

50 lines
901 B
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 "util.h"
static void head(FILE *, const char *, long);
int
main(int argc, char *argv[])
{
2011-06-10 04:41:40 +00:00
char c;
2011-05-25 10:42:17 +00:00
long n = 10;
FILE *fp;
while((c = getopt(argc, argv, "n:")) != -1)
switch(c) {
case 'n':
2011-06-10 13:55:01 +00:00
n = estrtol(optarg, 0);
2011-05-25 10:42:17 +00:00
break;
default:
exit(EXIT_FAILURE);
}
if(optind == argc)
head(stdin, "<stdin>", n);
else for(; optind < argc; optind++) {
if(!(fp = fopen(argv[optind], "r")))
eprintf("fopen %s:", argv[optind]);
head(fp, argv[optind], n);
fclose(fp);
}
return EXIT_SUCCESS;
}
void
head(FILE *fp, const char *str, long n)
{
char buf[BUFSIZ];
2011-05-25 19:40:47 +00:00
long i = 0;
2011-05-25 10:42:17 +00:00
2011-05-25 19:40:47 +00:00
while(i < n && fgets(buf, sizeof buf, fp)) {
2011-05-25 10:42:17 +00:00
fputs(buf, stdout);
2011-05-25 19:40:47 +00:00
if(buf[strlen(buf)-1] == '\n')
i++;
}
2011-05-25 10:42:17 +00:00
if(ferror(fp))
eprintf("%s: read error:", str);
}