// Common, group Files
// Copyright Alexander Liss

#ifndef __FILESTD_H__
#define __FILESTD_H__

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

// mode "w+" 
//	opens an empty file for both reading and writing. 
//	if the given file exists, its contents are destroyed
// mode "a+" 
//	opens for reading and appending; 
//	the appending operation includes the removal of the eof marker 
//	before new data is written to the file and 
//	the eof marker is restored after writing is complete; 
//	creates the file first if it doesn’t exist.

// destructor closes the file when a calling function (block) ends

struct FileStd
{

	FILE *p;

FileStd(const char *name,const char *mode="a+" ):p(0)
{if(name) p=fopen(name,mode);}
~FileStd(){ if(p) fclose(p); }

int read(int& actual,unsigned char * data, int limit);

//both set trailing zero
// reallocates, if needed
int read(CommBuffer& buf, int limit);
// read as much as can fit
int read(CommBuffer& buf);

int write(int& actual,const unsigned char * data, int size);
int write(int& actual,const CommBuffer& buf,ReadControl& c)
{return write(actual,buf.read_start(c),buf.data_left(c));}

bool file_end()
{if(feof(p)) return true; return false;}
};

#endif