summaryrefslogtreecommitdiff
path: root/cat.c
blob: 22b2c84b3494833ebc108226bd683d72c9ced35f (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
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  int choice;
  int show_lines = 0;

  while ( (choice = getopt(argc, argv, "n")) != -1 ) {
    switch(choice) {
      case 'n':
        show_lines = 1;
        break;
      case '?':
      default:
        break;
    }
  }
  argc -= optind;
  argv += optind;

  char *filename = argv[0];
  FILE *file = fopen(filename, "r");

  if (file) {
    int character, previous;
    int line = 0;

    if (show_lines == 1) {
      printf("%6d\t", ++line);
    }

    while( (character = getc(file)) != EOF ) {
      if (previous == '\n' && show_lines == 1) {
        printf("%6d\t", ++line);
      }
      putchar(character);
      previous = character;
    }
    fclose(file);
  }
  return 0;
}