#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>


struct rec {
	int x;
	int y;
	int z;
};

int tot_rec(FILE *fp)
{
	long int n;

	fseek(fp, 0L, SEEK_END);
	n = ftell(fp)/sizeof(struct rec);

	return n;
}

void f_write()
{
	int i;
	FILE *fp;
	struct rec my_record;

	fp=fopen("test.bin","wb");

	for ( i=0; i < 10; i++ ) {
		my_record.x = i;
		fwrite( &my_record, sizeof(struct rec), 1, fp );
	}

	fclose(fp);

	return;
}


void f_display()
{
	int i;
	long int n;
	FILE *fp;
	struct rec my_record;

	fp=fopen("test.bin","rb");

	n=tot_rec(fp);

	printf("File size is %ld bytes with %ld records\n", ftell(fp), n);

	fseek(fp, 0L, SEEK_SET);
	for ( i=0; i < n; i++) {
		fread(&my_record,sizeof(struct rec),1,fp);
		printf("%d\n",my_record.x);
	}
	printf("\n");

	fclose(fp);

	return;
}

void f_del_2()
{
	long int n;
	FILE *fp;
	struct rec my_record;

	fp=fopen("test.bin","r+b");

	n=tot_rec(fp);

	fseek( fp, sizeof(struct rec)*(n-1), SEEK_SET );
	fread( &my_record, sizeof(struct rec), 1, fp );

	fseek( fp, sizeof(struct rec)*1, SEEK_SET );
	fwrite( &my_record, sizeof(struct rec), 1, fp );

	truncate("test.bin", sizeof(struct rec)*(n-1) );

	fclose(fp);

}

int main()
{
	f_write();
	f_display();

	f_del_2();
	f_display();

	return 0;
}

