summaryrefslogtreecommitdiff
path: root/head.c
blob: f3f29a7564de9929178a40012737d51f7c91cf5c (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  int choice;
  int lines_to_print = 10;
  char *ep;

  while ( (choice = getopt(argc, argv, "n:")) != -1 ) {
    switch(choice) {
      case 'n':
        lines_to_print = strtol(optarg, &ep, 10);
        break;
      case '?':
      default:
        break;
    }
  }
  argc -= optind;
  argv += optind;

  FILE *file = fopen(argv[0], "r");
  if (file) {
    int character;

    while( (character = getc(file)) != EOF ) {
      putchar(character);
      if (character == '\n') {
        --lines_to_print;
      }
      if (lines_to_print == 0) {
        break;
      }
    }

    fclose(file);
    return 0;
  }
  else {
    return 1;
  }
}