/*
 * fileio.c  -  File I/O routines
 *
 * Copyright (C) 1998-2003 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  This program 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 2 of the License, or
 *  any later version.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: fileio.c,v 1.4 2003/01/25 23:29:44 gkminix Exp $
 */

#include <common.h>
#include <nblib.h>
#include "privlib.h"



/*
 * Global variables exported by this module
 */
unsigned long write_chksum = 0;	/* checksum for all bytes when writing */



/*
 * Read one block of data
 */
int nbread(buf, bufsize, infile)
__u8 *buf;
unsigned int bufsize;
int infile;
{
  int ofs;

  if (bufsize == 0)
	return(0);

  /*
   * We assume here that read() really reads the input file byte by byte,
   * and also stores each byte into a packed array of bytes. There do exist
   * systems with a character size different that one byte. How should we
   * handle those?
   */
  if ((ofs = read(infile, (char *)buf, bufsize)) < 0) {
	if (!quiet) perror(progname);
	exit(EXIT_READ);
  }
  return(ofs);
}



/*
 * Write one block of data to the output file.
 */
int nbwrite(buf, bufsize, outfile)
__u8 *buf;
unsigned int bufsize;
int outfile;
{
  int j, ofs;

  if (bufsize == 0)
	return(0);

  /*
   * Write buffer into output file. The same problem with read() above also
   * applies to write(). Can we assume, that it will write a packed array of
   * bytes correctly?
   */
  if ((ofs = write(outfile, (char *)buf, bufsize)) < 0) {
	if (!quiet) perror(progname);
	exit(EXIT_WRITE);
  }
  if (ofs != bufsize) {
	prnerr0("incorrect number of bytes written");
	exit(EXIT_WRITE);
  }

  /* Compute the checksum */
  for (j = 0; j < ofs; j++) {
	write_chksum += buf[j];
	write_chksum &= 0xffff;
  }
  return(ofs);
}



syntax highlighted by Code2HTML, v. 0.9.1