/*********************************************************************
 * This file is part of the cpplibs suite.
 *
 * Copyright (C) 2001 Topi Mäenpää
 * All rights reserved.
 *
 * This program is free software. You can redistribute and/or modify
 * it under the terms of the free software licence found in the
 * accompanying file "COPYING". The licence terms must always be
 * redistributed with this source file. The above copyright notice
 * must be reproduced in all modified and unmodified copies of this
 * source file.
 *
 * $Revision: 1.6 $
 *********************************************************************/

#include "GeneralFile.h"

using namespace std;

namespace util { namespace io {
	void GeneralFile::write(const void* msg, int len) throw (IOException&)
	{
		int sentTotal = 0;
		while (sentTotal < len)
			{
				int sent = ::write(fd,msg,len);
				if (sent == -1)
					throw IOException("Write: write failed");
				sentTotal += sent;
				(char*)msg += sent;
				len -= sent;
			}
	}

	void GeneralFile::write(int msg) throw (IOException&)
	{
		char bfr[MAXLEN];
		sprintf(bfr,"%d",msg);
		write(bfr);
	}

	void GeneralFile::write(float msg) throw (IOException&)
	{
		char bfr[MAXLEN];
		sprintf(bfr,"%.3f",msg);
		write(bfr);
	}

	string GeneralFile::readLine(void) throw (IOException&)
	{
		string line;
		char bfr;
		while (true)
			{
				read(&bfr,1);
				if (bfr != '\n')
					line += bfr;
				else
					break;
			}
		int len = line.size();
		if (line[len-1] == '\r')
			line.resize(len-1);
		return line;
	}
	
	void* GeneralFile::read(void* buf, int len) throw (IOException&)
	{
		int receivedTotal = 0;
		void *start = buf;
		int readNext = len;
		while (receivedTotal < len)
			{
				int received = ::read(fd,start,readNext);
				if (received == -1)
					throw IOException("Read: read failed");
				receivedTotal += received;
				(char*)start += received;
				readNext -= received;
			}
		return buf;
	}

	void GeneralFile::close(void) throw (IOException&)
	{
		if (::close(fd) == -1)
			throw IOException("Close: cannot close");		
	}
}}
