add head
parent
a9c970b973
commit
262f357fdd
@ -0,0 +1,15 @@
|
||||
.TH HEAD 1 sbase\-VERSION
|
||||
.SH NAME
|
||||
head \- output first part of files
|
||||
.SH SYNOPSIS
|
||||
.B head
|
||||
.RB [ \-n
|
||||
.IR lines ]
|
||||
.RI [ file ...]
|
||||
.SH DESCRIPTION
|
||||
.B head
|
||||
writes the first 10 lines of each file to stdout.
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
.BI \-n " lines"
|
||||
outputs the given number of lines.
|
@ -0,0 +1,47 @@
|
||||
/* See LICENSE file for copyright and license details. */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include "util.h"
|
||||
|
||||
static void head(FILE *, const char *, long);
|
||||
|
||||
int
|
||||
main(int argc, char *argv[])
|
||||
{
|
||||
char *end, c;
|
||||
long n = 10;
|
||||
FILE *fp;
|
||||
|
||||
while((c = getopt(argc, argv, "n:")) != -1)
|
||||
switch(c) {
|
||||
case 'n':
|
||||
n = strtol(optarg, &end, 0);
|
||||
if(*end != '\0')
|
||||
eprintf("%s: not a number\n", optarg);
|
||||
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];
|
||||
int i;
|
||||
|
||||
for(i = 0; i < n && fgets(buf, sizeof buf, fp); i++)
|
||||
fputs(buf, stdout);
|
||||
if(ferror(fp))
|
||||
eprintf("%s: read error:", str);
|
||||
}
|
Loading…
Reference in New Issue