-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhead.c
More file actions
50 lines (45 loc) · 967 Bytes
/
head.c
File metadata and controls
50 lines (45 loc) · 967 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
static void head(FILE *, const char *, long);
int
main(int argc, char *argv[])
{
char c;
long n = 10;
FILE *fp;
while((c = getopt(argc, argv, "n:")) != -1)
switch(c) {
case 'n':
n = estrtol(optarg, 0);
break;
default:
exit(EXIT_FAILURE);
}
if(optind == argc)
head(stdin, "<stdin>", n);
else for(; optind < argc; optind++) {
if(strcmp(argv[optind], "-") == 0) argv[optind] = "/dev/stdin";
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];
long i = 0;
while(i < n && fgets(buf, sizeof buf, fp)) {
fputs(buf, stdout);
if(buf[strlen(buf)-1] == '\n')
i++;
}
if(ferror(fp))
eprintf("%s: read error:", str);
}