
/*
	Listing 3
*/

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "enet_cs.h"

#define NOMOD 65535

FILE *fp;

char filename[100] = "node\"test tester\"::[test]file.txt";
cs_write(long loc, int value)
{

	char *sptr;

	while ((fp = fopen(filename, "a+")) == NULL){

		if (errno != NOMOD) {

			if ( (sptr = strerror(errno)) == NULL) {
				printf ("Unknown open error.\n");
				exit(0);
			} else {
				sptr = strerror(errno);
				perror (sptr);
				exit(0);
			}

		}

	};

	if (fseek (fp, loc*4, ORIGIN) != 0)
		printf ("ERROR: fseek error in cs_write\n");

	if (fprintf (fp, "%d ", value) < 0)
		printf ("ERROR: cs_write error\n");

	fclose (fp);

	return;
}

int cs_read(long loc)
{

	char *sptr;
	int value;

	while ((fp = fopen(filename, "r")) == NULL){

		if (errno != NOMOD) {

			if ((sptr = strerror(errno)) == NULL) {
				printf ("Unknown open error.\n");
				exit(0);
			} else {
				sptr = strerror(errno);
				perror (sptr);
				exit(0);
			}

		}

	};

	if (fseek (fp, loc*4, ORIGIN) != 0)
		printf ("ERROR: fseek error in cs_read\n");
	if (fscanf (fp ,"%d", &value) == EOF)
		printf ("ERROR: cs_read error\n");

	fclose (fp);

	return(value);
}

