/*
 * File:
 *   rdln.c
 * Author:
 *   Samuel A. Rebelsky
 * Version:
 *   1.0 of March 2003.
 * Summary:
 *   An implementation of the rdln procedure from CSC195 Exam 2.
 */

/********************************************************************* 
 * Headers *
 ***********/

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include "rdln.h"


/********************************************************************* 
 * Exported Procedures *
 ***********************/

/* See rdln.h for documentation. */
char *rdln(FILE *file)
{
  int i;	/* Counter variable. */
  int len=0;	/* Length of the string. */
  char *str;	/* The string to be read. */
  int ch;	/* Temporary character for reading. */
  /* Determine the length of the string. */
  for (ch=getc(file); isdigit(ch); ch=getc(file))
    len = len*10 + (ch - '0');  /* Assume we're using ASCII. */   
  /* Undo the extra character read. */
  ungetc(ch, file);
  /* Allocate the string. */
  str = malloc(len+1);
  /* Sanity check. */
  if (str == NULL) return NULL;
  /* Read the characters. */
  for (i = 0; i < len; i++)
    str[i] = (char) getc(file);
  /* Drop the newline. */
  getc(file);
  /* Add the end-of-string mark. */
  str[len] = '\0';
  /* That's it, we're done. */
  return str;
} /* rdln(FILE *) */
