#define _GNU_SOURCE #include #include #include #include // You may assume that lines are no longer than 1024 bytes #define LINELEN 1024 static void usage (void) __attribute__ ((unused)); int main (int argc, char *argv[]) { int opt; int n = 5; while ((opt = getopt (argc, argv, "n:")) != -1) { switch (opt) { case 'n': n = strtol (optarg, NULL, 10); break; default: printf ("./bin/head: invalid option -- \'%c\'\n", optopt); exit (EXIT_FAILURE); } } FILE *file = optind < argc ? fopen (argv[optind], "r") : stdin; if (file == NULL) { perror ("Failed to open input file"); exit (EXIT_FAILURE); } char buffer[LINELEN]; int count = 0; while (count < n && fgets (buffer, sizeof (buffer), file) != NULL) { printf ("%s", buffer); count++; } return EXIT_SUCCESS; } static void usage (void) { printf ("head, prints the first few lines of a file\n"); printf ("usage: head [FLAG] FILE\n"); printf ("FLAG can be:\n"); printf (" -n N show the first N lines (default 5)\n"); printf ("If no FILE specified, read from STDIN\n"); }