k9core

Coreutils for *nix operating systems [fork]
git clone git://bvnf.space/k9core.git
Log | Files | Refs | LICENSE

head.c (1029B)


      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
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int
head(int fd, int lines)
{
	int a;
	ssize_t r;
	int c = 0;

	while((r = read(fd, &a, 1)) > 0) {
		if(r == -1) {
			fprintf(stderr, "head: %s\n", strerror(errno));
			return 1;
		}
		if((char)a == '\n')
			++c;

		putchar(a);
		if(c == lines)
			break;
	}
	return 0;
}

int
main(int argc, char *argv[])
{
	int lines = 10;
	int return_value = 0;
	int c, fd;
	c = getopt(argc, argv, "n:");
	switch(c) {
		case 'n':
			lines = atoi(optarg);
			if(lines == 0) {
				fprintf(stderr, "head: invalid number '%s'\n", optarg);
				return 1;
			}
			break;
		case ':':
		case '?':
			fprintf(stderr, "usage: head [-n N] file\n");
			return 1;
	}

	if(optind == argc)
		fd = 0;
	else {
		fd = open(argv[optind], O_RDONLY);
		if(fd == -1) {
			fprintf(stderr, "head: %s: %s\n", argv[optind], strerror(errno));
			return 1;
		}
	}
	return_value = head(fd, lines);
	close(fd);
	return return_value;
}