/*
 * FILEIO.C
 * The routines in this file read and write ASCII files from the disk.
 * Modified for OS/2 to use file buffering.  This is just an ANSI feature
 *   so should be portable.
 */

/* C Durland	Public Domain
 * J Burnell	OS/2ized.  3/92
 */

#include <stdio.h>
#include "me2.h"

#define BufferSize 1024
static char FileBuffer [BufferSize];

static FILE *ffp = NULL;	/* File pointer, all functions. (sleaze) */

	/* Open a file for reading */
ffropen(fn) char *fn;
{
  if ((ffp = fopen(fn,"r")) == NULL) return FIOFNF;
  setvbuf (ffp, FileBuffer, _IOFBF, BufferSize);
  return FIOSUC;
}

	/* Open a file for writing  */
ffwopen(fn) char *fn;
{
  if ((ffp = fopen(fn,"w")) == NULL)
	{ mlwrite("Cannot open file for writing"); return FIOERR; }
  return FIOSUC;
}

	/* Close a file. Should look at the status on all systems */
ffclose()
{
  if (fclose(ffp)) { mlwrite("Error closing file"); return FIOERR; }
  return FIOSUC;
}

/*
 * Write a line to the already opened file.
 * n is the line length, less the free newline. Return the status.
 * Check only at the newline.
 */
ffputline(buf,n) unsigned char *buf; int n;
{
  fwrite(buf,n,1,ffp); fputc('\n',ffp);
  if (ferror(ffp)) { mlwrite("Write I/O error"); return FIOERR; }
  return FIOSUC;
}

/*
 * Read a line from a file and store the bytes in the supplied buffer.
 * n is the length of the buffer, counting the '\0'.
 * Complain about long lines and lines at the end of the file that don't
 * have a newline present. Check for I/O errors too. Return status.
 */
ffgetline(buf,n) register char buf[]; int n;
{
  register char *ptr;

  if (fgets(buf,n,ffp) == NULL) return FIOEOF;
  if (*(ptr = buf + strlen(buf) - 1) == '\n') *ptr = '\0';
  return FIOSUC;
}
