micro-utils/src/coreutils/head/head.c

94 lines
1.5 KiB
C

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "config.h"
char v_flag;
char c_flag;
long parse_long(const char *str) {
char *ptr;
long ret = strtol(str, &ptr, 0);
if (*ptr) {
fprintf(stderr, "head: %s invalid number\n", ptr);
exit(1);
}
return ret;
}
void print(const char *file, FILE *fp, long lines, long bytes) {
if (v_flag)
printf(HEAD_FMT, file);
long lcount = 0;
long bcount = 0;
while (1) {
int c = getc(fp);
bcount++;
if (c == '\n')
lcount++;
if (c == EOF || lcount == lines || (c_flag && bcount == bytes))
break;
putchar(c);
}
}
int main(int argc, char **argv) {
long lines = 10;
long bytes = 0;
int opt;
while ((opt = getopt(argc, argv, "n:c:v")) != -1) {
switch (opt) {
case 'n':
lines = parse_long(optarg);
break;
case 'c':
c_flag = 1;
bytes = parse_long(optarg);
break;
case 'v':
v_flag = 1;
break;
default:
printf("head [ncv] [file1 file2...]\n\t-n Print N lines\n\t-c Print N bytes\n\t-v Print headers\n");
return 0;
}
}
argv += optind;
argc -= optind;
if (argc == 0)
print("-", stdin, lines, bytes);
for (int i = 0; i < argc; i++) {
FILE *fp = NULL;
if (argv[i][0] == '-')
fp = stdin;
else
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "head: %s: %s\n", argv[i], strerror(errno));
return 1;
}
print(argv[i], fp, lines, bytes);
fclose(fp);
}
return 0;
}