morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

head.c (1243B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 #include <unistd.h>
      6 
      7 #include "text.h"
      8 #include "util.h"
      9 
     10 static void head(FILE *, const char *, long);
     11 
     12 static void
     13 usage(void)
     14 {
     15 	eprintf("usage: %s [-n lines] [file...]\n", argv0);
     16 }
     17 
     18 int
     19 main(int argc, char *argv[])
     20 {
     21 	long n = 10;
     22 	FILE *fp;
     23 	int ret = 0;
     24 	int newline, many;
     25 
     26 	ARGBEGIN {
     27 	case 'n':
     28 		n = estrtol(EARGF(usage()), 0);
     29 		break;
     30 	ARGNUM:
     31 		n = ARGNUMF(0);
     32 		break;
     33 	default:
     34 		usage();
     35 	} ARGEND;
     36 
     37 	if (argc == 0) {
     38 		head(stdin, "<stdin>", n);
     39 	} else {
     40 		many = argc > 1;
     41 		for (newline = 0; argc > 0; argc--, argv++) {
     42 			if (!(fp = fopen(argv[0], "r"))) {
     43 				weprintf("fopen %s:", argv[0]);
     44 				ret = 1;
     45 				continue;
     46 			}
     47 			if (many)
     48 				printf("%s==> %s <==\n",
     49 				       newline ? "\n" : "", argv[0]);
     50 			newline = 1;
     51 			head(fp, argv[0], n);
     52 			fclose(fp);
     53 		}
     54 	}
     55 	return ret;
     56 }
     57 
     58 static void
     59 head(FILE *fp, const char *str, long n)
     60 {
     61 	char *buf = NULL;
     62 	size_t size = 0;
     63 	ssize_t len;
     64 	unsigned long i = 0;
     65 
     66 	while (i < n && ((len = getline(&buf, &size, fp)) != -1)) {
     67 		fputs(buf, stdout);
     68 		if (buf[len - 1] == '\n')
     69 			i++;
     70 	}
     71 	free(buf);
     72 	if (ferror(fp))
     73 		eprintf("%s: read error:", str);
     74 }