#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

struct record
{
    char name[80];
    char addr[80];
    char phone[80];
};

main (int argc, char *argv[])
{
	int idx;
	struct record buf;
	int fd;

	if (argc < 2)
	{
		fprintf(stderr, "Usage: <recno> <name> <address> <phone>\n");
		exit(0);
	}

	idx = atoi(argv[1]);

	if ((fd = open("database", O_RDWR | O_CREAT, 0644)) == -1)
	{
		fprintf(stderr, "Unable to open input file %s\n",argv[1]);
		exit(1);
	}

	if (argc == 2)
	{
		printf("Getting database index = %d\n",idx);
		lseek(fd, idx*sizeof(buf), SEEK_SET);
		if (read(fd, &buf, sizeof(buf)) < 0)
		{
			fprintf(stderr, "Record not found\n");
			exit(3);
		}

		puts(buf.name);
		puts(buf.addr);
		puts(buf.phone);
	}
	else
	{
		printf("Adding database index = %d\n",idx);
		strcpy(buf.name, argv[2]);
		strcpy(buf.addr, argv[3]);
		strcpy(buf.phone,argv[4]);

		if (lseek(fd, idx*sizeof(buf), SEEK_SET) < 0)
		{
			fprintf(stderr, "Seek Error\n");
			exit(4);
		}
		if (write(fd, &buf, sizeof(buf)) < 0)
		{
			perror("Error writing to file\n");
			exit(4);
		}
	}

	close(fd);
	exit(0);
}
