#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "dbf.h"

main(int argc, char **argv) {
int handle;
unsigned short rec_num;
DBF_HEAD dbf_head;
char *record;

if (argc!=2) {
   printf("\nUsage:    dbread <filename>\n");
   exit(0);
   }
if ((handle=open(argv[1], O_RDONLY))<0) {
   printf("\nCan not open database file: '%s'\n", argv[1]);
   exit(0);
   }

if (read(handle, (char*)&dbf_head, sizeof(dbf_head))!=sizeof(DBF_HEAD)) {
   printf("\nError: Short file ... header dammaged!\n");
   exit(0);   
   }
printf("Database:      %s\n", argv[1]);
printf("DBF ID:        %d\n", dbf_head.dbf_id);
printf("Last update:   %d %d %d\n", dbf_head.last_update[0], dbf_head.last_update[1], dbf_head.last_update[2]);
printf("Data position: %d\n", dbf_head.data_offset);
printf("Record size:   %d\n", dbf_head.rec_size);
printf("Record number: %1d\n", dbf_head.last_rec);

if (lseek(handle, (long)dbf_head.data_offset, 0)<0) {
   printf("Error: Seek error ... short data]n");
   exit(0);
   }

record=(char*)malloc(dbf_head.rec_size);
printf("\n\n");

for (rec_num=1; rec_num<=dbf_head.last_rec; rec_num++) {
   read(handle, record, dbf_head.rec_size);
   printf("%4d", rec_num);
   
   printf("%c ", record[0]);
   printf("%.*s\n", dbf_head.rec_size, record);
   }


close(handle);

}
