/*
 * @(#)PrintWriter.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 *
 * Jörg Haeger, 22.04.2002
 */

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "Error.h"
#include "PrintWriter.h"
#include "String.h"
#include "StringBuffer.h"

PrintWriter::PrintWriter(int fd) {
	int fdDup = dup(fd);
	if (fdDup == -1)
		throw new Exception("PrintWriter::PrintWriter: dup %d %s",
			errno, strerror(errno));

	out = fdopen(fdDup, "w");
	if (out == NULL)
		throw new Exception("PrintWriter::PrintWriter: fdopen %d %s",
			errno, strerror(errno));
}

PrintWriter::PrintWriter(PrintWriter *writer) {
	out = writer->out;
	writer->out = NULL;
	delete writer;
}

PrintWriter::~PrintWriter() {
	if (out != NULL)
		close();
}

void PrintWriter::close() {
	flush();
	fclose(out);
}

void PrintWriter::flush() {
	fflush(out);
}

void PrintWriter::write(const char *str) {
	fprintf(out, "%s", str);
}

void PrintWriter::write(const char *buf, int off, int len) {
	int n = fwrite(&buf[off], 1, len, out);
}

void PrintWriter::write(String &s) {
	for (int i = 0; i < s.length(); i++)
		fprintf(out, "%c", s.charAt(i));
}

void PrintWriter::write(StringBuffer &s) {
	for (int i = 0; i < s.length(); i++)
		fprintf(out, "%c", s.charAt(i));
}
