/*
 *  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
 *  (at your option) 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */


//
// Class: cFile
//
// Created by: Kristian Mueller <Kristian-M@Kristian-M.de>
// Created on: Sat Jun 18 15:40:21 2005
//

#include "cFile.h"
#include "cData.h"


cFile::cFile(){
    iDescriptor = 0;
    bEof = false;
    sFileName = "";
}


cFile::~cFile(){
    closeFile();
}


bool cFile::openFile( const std::string sInFileName, const int iMode){
    if(isOpen())
        return false;

    if((iDescriptor = open(sInFileName.c_str(), iMode)) < 0){
        iDescriptor = 0;
        perror("file not open");
        return false;
    }
	sFileName = sInFileName;

    return true;
}

bool cFile::createFile( const std::string sInFileName, const int iMode){
    if(isOpen())
        return false;

	if((iDescriptor = creat(sInFileName.c_str(), iMode)) < 0){
        iDescriptor = 0;
        perror("file not created");
        return false;
    }
	
	sFileName = sInFileName;
    return true;
}

void cFile::closeFile(void){
    if(isOpen()){
    	close(iDescriptor);
        iDescriptor = 0;
    }
}

const unsigned long cFile::writeToFile(cData &aInData) const{
    return write(iDescriptor, aInData.getData(), aInData.getLength());
}

const unsigned long cFile::writeToFile(const char iCharacter) const{
    return write(iDescriptor, &iCharacter, 1);
}

const int cFile::readFromFile( char* sBuffer, const unsigned long iInLength){
    unsigned long iLenght;

    if (!bEof){
        if ((iLenght = read(iDescriptor, sBuffer, iInLength)) == -1){
            perror("Error reading from file descriptor");
            return 0;
        };

        bEof = (bool) ((unsigned int) iLenght != iInLength);
        return iLenght;
    }
}

const unsigned long cFile::readFromFile(char& iCharacter){
    return read(iDescriptor, &iCharacter, 1);
}

const std::string cFile::readString(const int iInLength){
	char sChar[iInLength+1];

    if (iDescriptor != 0){
        read(iDescriptor, &sChar, iInLength);
        sChar[iInLength+1] = '\0';
        return sChar;
    } 
    return "";
}

