// Example C program firstline.c
// Author: Norman Carver
// Will read and then print the first line
// from a file specified on the command line.
//
// Compile using:
//   gcc -Wall -o firstline firstline.c
// Call as:
//   firstline FILE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MAX_LINE_LENGTH 100


//Prototypes:
char *get_line(FILE *fpntr);


int main(int argc, char *argv[])
{
  char *file_pathname, *first_line;
  FILE *fpntr;

  //Check for proper number of arguments:
  if (argc != 2) {
    fprintf(stderr,"Usage: firstline FILE\n");
    return EXIT_FAILURE; 
  }

  //Get source and destination from arguments:
  file_pathname = argv[1];

  //Open file for reading:
  if ((fpntr = fopen(file_pathname, "r")) == NULL) {
    fprintf(stderr,"Error opening file %s: %s\n",file_pathname, strerror(errno));
    return EXIT_FAILURE;
  }

  //Get first line from file:
  if ((first_line = get_line(fpntr)) == NULL) {
    perror("Error reading line");
    exit(EXIT_FAILURE);
  }

  //Print out line:
  printf("First line in file %s:\n%s",file_pathname,first_line);
  //Close file:
  fclose(fpntr);

  //Normal termination:
  return EXIT_SUCCESS;
}

//Function to get next line from open file and place it as a legal string into
//a line buffer that is created locally and is static so it can be returned.
//Returns pointer to line buffer, or else NIL on error or immediate EOF.
char *get_line(FILE *fpntr)
{
  static char line_buff[MAX_LINE_LENGTH];

  //Get first line from file and return
  if (fgets(line_buff,MAX_LINE_LENGTH,fpntr) != NULL)
    return line_buff;
  else
    return NULL;
}

// EOF

