/*
 * Copyright 2011 Steven Gribble
 *
 *  This file is the solution to an exercise problem posed during
 *  one of the UW CSE 333 lectures (333exercises).
 *
 *  333exercises is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  333exercises is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with 333exercises.  If not, see <http://www.gnu.org/licenses/>.
 */

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

#include "readlinefromfile.h"

// A helper function to strip a trailing newline from string buf,
// if one is present.
static void StripTrailingNewline(char *buf);

int ReadNextLine(FILE *f, char **retbuf) {
  ssize_t returnval;
  size_t  n;

  // Read from f using the Linux system call getline().
  returnval = getline(retbuf, &n, f);
  if (returnval == -1) {
    // the read failed
    return 0;
  }
  assert(*retbuf != NULL);  // A quick sanity check.

  // Strip the trailing newline, if there is any.
  StripTrailingNewline(*retbuf);
  return 1;
}

static void StripTrailingNewline(char *buf) {
  int len = strlen(buf);
  if (len == 0)
    return;
  if (buf[len-1] == '\n')
    buf[len-1] = '\0';
}